node.js 使用 Express 4.0 上传文件:req.files 未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23114374/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
File uploading with Express 4.0: req.files undefined
提问by safwanc
I'm attempting to get a simple file upload mechanism working with Express 4.0 but I keep getting undefinedfor req.filesin the app.postbody. Here is the relevant code:
我试图得到一个简单的文件上传机制的工作与快车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');
});
.. and the accompanying Pug code:
.. 以及随附的 Pug 代码:
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 mscdexbelow, I've switched to using busboyinstead of bodyParser:
解决方案
多亏了下面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');
});
});
});
采纳答案by mscdex
The body-parsermodule only handles JSON and urlencoded form submissions, not multipart (which would be the case if you're uploading files).
该body-parser模块仅处理 JSON 和 urlencoded 表单提交,而不处理多部分(如果您正在上传文件,则会出现这种情况)。
For multipart, you'd need to use something like connect-busboyor multeror 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.
对于多,你需要使用类似connect-busboy或multer或connect-multiparty(多方/强大的是什么快递bodyParser中间件最初使用)。同样 FWIW,我正在 busboy 之上开发一个更高级别的层,称为reformed. 它带有一个 Express 中间件,也可以单独使用。
回答by Anton Stafeyev
Here is what i found googling around:
这是我在谷歌搜索中发现的:
var fileupload = require("express-fileupload");
app.use(fileupload());
Which is pretty simple mechanism for uploads
这是一个非常简单的上传机制
app.post("/upload", function(req, res)
{
var file;
if(!req.files)
{
res.send("File was not found");
return;
}
file = req.files.FormFieldName; // here is the field name of the form
res.send("File Uploaded");
});
回答by HPierce
It looks like body-parserdidsupport uploading files in Express 3, but support was dropped for Express 4 when it no longer included Connect as a dependency
它看起来body-parser确实支持在 Express 3 中上传文件,但是当 Express 4不再包含 Connect 作为依赖项时,它的支持被取消了
After looking through some of the modules in mscdex's answer, I found that express-busboywas a far better alternative and the closest thing to a drop-in replacement. The only differences I noticed were in the properties of the uploaded file.
在浏览了 mscdex 答案中的一些模块后,我发现这express-busboy是一个更好的替代方案,也是最接近替代方案的方法。我注意到的唯一区别在于上传文件的属性。
console.log(req.files)using body-parser(Express 3) output an object that looked like this:
console.log(req.files)使用body-parser(Express 3) 输出一个如下所示的对象:
{ file:
{ fieldName: 'file',
originalFilename: '360px-Cute_Monkey_cropped.jpg',
name: '360px-Cute_Monkey_cropped.jpg'
path: 'uploads/6323-16v7rc.jpg',
type: 'image/jpeg',
headers:
{ 'content-disposition': 'form-data; name="file"; filename="360px-Cute_Monkey_cropped.jpg"',
'content-type': 'image/jpeg' },
ws:
WriteStream { /* ... */ },
size: 48614 } }
compared to console.log(req.files)using express-busboy(Express 4):
与console.log(req.files)使用express-busboy(Express 4) 相比:
{ file:
{ field: 'file',
filename: '360px-Cute_Monkey_cropped.jpg',
file: 'uploads/9749a8b6-f9cc-40a9-86f1-337a46e16e44/file/360px-Cute_Monkey_cropped.jpg',
mimetype: 'image/jpeg',
encoding: '7bit',
truncated: false
uuid: '9749a8b6-f9cc-40a9-86f1-337a46e16e44' } }
回答by Parth Raval
multeris a middleware which handles “multipart/form-data” and magically & makes the uploaded files and form data available to us in request as request.files and request.body.
multer是一个中间件,它处理“multipart/form-data”并神奇地将上传的文件和表单数据以 request.files 和 request.body 的形式提供给我们。
installing multer :- npm install multer --save
安装multer:- npm install multer --save
in .html file:-
在 .html 文件中:-
<form method="post" enctype="multipart/form-data" action="/upload">
<input type="hidden" name="msgtype" value="2"/>
<input type="file" name="avatar" />
<input type="submit" value="Upload" />
</form>
in .js file:-
在 .js 文件中:-
var express = require('express');
var multer = require('multer');
var app = express();
var server = require('http').createServer(app);
var port = process.env.PORT || 3000;
var upload = multer({ dest: 'uploads/' });
app.use(function (req, res, next) {
console.log(req.files); // JSON Object
next();
});
server.listen(port, function () {
console.log('Server successfully running at:-', port);
});
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/file-upload.html');
})
app.post('/upload', upload.single('avatar'), function(req, res) {
console.log(req.files); // JSON Object
});
Hope this helps!
希望这可以帮助!
回答by Dmitry Kulahin
1) Make sure that your file is really sent from the client side. For example you can check it in Chrome Console: screenshot
1)确保您的文件确实是从客户端发送的。例如,您可以在 Chrome 控制台中查看: 截图
2) Here is the basic example of NodeJS backend:
2)这是NodeJS后端的基本示例:
const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();
app.use(fileUpload()); // Don't forget this line!
app.post('/upload', function(req, res) {
console.log(req.files);
res.send('UPLOADED!!!');
});
回答by Gaurav kumar
Please use below code
请使用以下代码
app.use(fileUpload());
回答by Sharl Sherif
PROBLEM SOLVED !!!!!!!
问题解决了 !!!!!!!
Turns out the storagefunction DID NOT run even once.
because i had to include app.use(upload)as upload = multer({storage}).single('file');
原来该storage功能甚至一次都没有运行。因为我必须包括app.use(upload)作为upload = multer({storage}).single('file');
let storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, './storage')
},
filename: function (req, file, cb) {
console.log(file) // this didn't print anything out so i assumed it was never excuted
cb(null, file.fieldname + '-' + Date.now())
}
});
const upload = multer({storage}).single('file');
回答by trd
express-fileuploadlooks like the only middleware that still works these days.
express-fileupload看起来是目前唯一仍然有效的中间件。
With the same example, multerand connect-multipartygives an undefined value of req.fileor req.files, but express-fileuploadworks.
使用相同的示例,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.
并且有很多关于req.file/req.files的空值的问题和问题。

