问题描述
我正在尝试使用 Express 4.0 获得一个简单的文件上传机制,但我一直在 app.postreq.files
获取 undefined
/代码> 身体.相关代码如下:
I'm attempting to get a simple file upload mechanism working with Express 4.0 but I keep getting undefined
for req.files
in the app.post
body. Here is the relevant code:
var bodyParser = require('body-parser');
var methodOverride = require('method-override');
//...
app.use(bodyParser({ uploadDir: path.join(__dirname, 'files'), keepExtensions: true }));
app.use(methodOverride());
//...
app.post('/fileupload', function (req, res) {
console.log(req.files);
res.send('ok');
});
.. 以及随附的 Pug 代码:
.. and the accompanying Pug code:
form(name="uploader", action="/fileupload", method="post", enctype="multipart/form-data")
input(type="file", name="file", id="file")
input(type="submit", value="Upload")
解决方案
感谢下面 mscdex 的回应,我已经改用 busboy
而不是 bodyParser
:
Solution
Thanks to the response by mscdex below, I've switched to using busboy
instead of bodyParser
:
var fs = require('fs');
var busboy = require('connect-busboy');
//...
app.use(busboy());
//...
app.post('/fileupload', function(req, res) {
var fstream;
req.pipe(req.busboy);
req.busboy.on('file', function (fieldname, file, filename) {
console.log("Uploading: " + filename);
fstream = fs.createWriteStream(__dirname + '/files/' + filename);
file.pipe(fstream);
fstream.on('close', function () {
res.redirect('back');
});
});
});
推荐答案
body-parser
模块只处理 JSON 和 urlencoded 表单提交,而不是 multipart(如果你上传文件就是这种情况).
The body-parser
module only handles JSON and urlencoded form submissions, not multipart (which would be the case if you're uploading files).
对于多部分,您需要使用类似connect-busboy
或 multer
或 connect-multiparty
(multiparty/formidable 最初用于 express bodyParser 中间件).同样 FWIW,我正在 busboy 之上开发一个更高级别的层,称为 reformed
.它带有一个 Express 中间件,也可以单独使用.
For multipart, you'd need to use something like connect-busboy
or multer
or connect-multiparty
(multiparty/formidable is what was originally used in the express bodyParser middleware). Also FWIW, I'm working on an even higher level layer on top of busboy called reformed
. It comes with an Express middleware and can also be used separately.
这篇关于使用 Express 4.0 上传文件:req.files 未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!