我试图得到一个简单的文件上传机制的工作与快车4.0,但我不断收到undefined
对req.files
在app.post
体内。以下是相关代码:
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');
});
..和随附的帕格代码:
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
:
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');
});
});
});
express-fileupload
看起来是当今唯一仍然有效的中间件。在相同的示例中,
multer
并connect-multiparty
给出了req.file或req.files的未定义值,但是express-fileupload
可以工作。And there are a lot of questions and issues raised about the empty value of req.file/req.files.