当我使用Multer for NodeJS通过HTTP接收文件时,req.file对象是未定义的。我可以看到文件以正确的文件夹结尾,但是名称乱码。不确定是否相关,但是我正在将Apache2与Ubuntu一起使用。
var express = require('express');
var app = express();
var fs = require('fs');
var multer = require('multer');
var upload = multer({ dest: 'uploads/' })
var bodyParser = require('body-parser');
app.use(express.static('public'));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({dest: '/var/www/185.86.150.191/uploads'}).any());
app.get('/index.html', function (req, res) {
res.sendFile( __dirname + "/" + "index.html" );
})
app.post('/file_upload', upload.single('file'), function (req, res) {
console.log(req.baseURL)
console.log(req.path)
console.log(req.file.name);
console.log(req.file.path);
console.log(req.file.type);
var file = __dirname + "/" + req.file.name;
fs.readFile( req.file.file.path, function (err, data) {
fs.writeFile(file, data, function (err) {
if( err ) {
console.log( err );
} else {
response = {
message:'File uploaded successfully',
filename:req.file.file.name
};
}
console.log( response );
res.end( JSON.stringify( response ) );
});
});
})
整个对象不是未定义的。我可以毫无问题地访问req.path,但是应用程序在到达req.file.name时崩溃,因为req.file是未定义的。
TypeError:无法读取未定义的属性“名称” 在/home/asgeir/nodejs/first_test_app/server.js:20:24 在Layer.handle [作为handle_request](/home/asgeir/nodejs/first_test_app/node_modules/express/lib/router/layer.js:95:5) 在下一个(/home/asgeir/nodejs/first_test_app/node_modules/express/lib/router/route.js:137:13) 立即。 (/home/asgeir/nodejs/first_test_app/node_modules/multer/lib/make-middleware.js:53:37) 在Instant.immediate._onImmediate(timers.js:440:18) 在processImmediate [as _immediateCallback](timers.js:383:17)
我发现的一个解决方法是将目标路径设置为绝对路径,但这没有帮助。 req.file对象仍未定义。
客户端看起来像这样:
<html>
<head>
<title>File Upload Testing</title>
</head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action = "http://185.86.150.191/node/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 :(得分:0)
我认为应该是req.files
,而不是req.file
答案 1 :(得分:0)
我已经编写了示例示例,请检查上面的示例,希望对您有帮助。
var multer = require('multer');
var upload = multer({dest: 'uploads/'});
app.post('/upload', upload.single(), function (req, res) {
console.log(req.file)
})