我正在测试Express的例子,但我遇到了这个问题。
我正在尝试执行此代码示例(从网上获取的示例),当我尝试上传图片时出现此错误。
TypeError: Cannot read property 'file' of undefined
SERVER
var express = require('express');
var app = express();
var fs = require("fs");
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
var multer = require('multer');
app.get('/index.html', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
app.post('/file_upload', function (req, res) {
console.log(req.files.file.name);
console.log(req.files.file.path);
console.log(req.files.file.type);
var file = __dirname + "/" + req.files.file.name;
fs.readFile( req.files.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if( err ){
console.log( err );
}else{
response = {
message:'File uploaded successfully',
filename:req.files.file.name
};
}
console.log( response );
res.end( JSON.stringify( response ) );
});
});
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
客户
<html>
<head>
<title>File Uploading Form</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action = "http://127.0.0.1:8081/file_upload" method = "POST"
enctype = "multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type = "submit" value = "Upload File" />
</form>
</body>
</html>
答案 0 :(得分:1)
试试这个......
<html>
<head>
<title>File Upload</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action = "http://127.0.0.1:8081/file_upload" method = "POST"
enctype = "multipart/form-data">
<input type="file" name="foo" size="50" />
<br />
<input type = "submit" value = "Upload File" />
</form>
</body>
</html>
Server.js
var express = require('express');
var app = express();
var path = require("path");
var bodyParser = require('body-parser');
var multer = require('multer');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.get('/index.html', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
var upload = multer({
dest: path.join(__dirname, '../public/upload/temp')
});
app.post('/file_upload', upload.single('foo'), function(req, res) {
if (req.file) {
console.dir(req.file);
return res.end('Uploaded successfuly');
}
res.end('No file found');
});
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
对于多上传更改upload.single(&#39; foo&#39;)到upload.array(&#39; foo&#39;)