问题描述
我试图获得一个简单的文件上传机制与Express 4.0工作,但我不断获得未定义
为 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 file,name =file,id =file)
input(type =submit,value =Upload)
解决方案
感谢,我已经切换到使用 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(上传:+ filename);
fstream = fs.createWriteStream(__ dirname + '/ files /'+ filename);
file.pipe(fstream);
fstream.on('close',function(){
res.redirect('back');
});
});
});
模块只处理JSON和urlencoded表单提交,而不是multipart如果你正在上传文件,那么你可以使用或或(多方/强大是最初在express bodyParser中间件中使用的)。另外FWIW,我正在一个更高级别的层面上,名叫。它配有Express中间件,也可以单独使用。
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');
});
.. and the accompanying Jade code:
form(name="uploader", action="/fileupload", method="post", enctype="multipart/form-data")
input(type="file", name="file", id="file")
input(type="submit", value="Upload")
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');
});
});
});
The body-parser
module only handles JSON and urlencoded form submissions, not multipart (which would be the case if you're uploading files).
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.
这篇关于文件上传速成版4.0:req.files未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!