javascript 使用 multer 上传文件时 req.files 未定义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32000516/
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
req.files is undefined when uploading file with multer
提问by arne.z
I am trying to build a Node.js Application in Express.js 4 that uploads an image. I decided to use the multer
module but cannot access the uploaded file through req.files
.
Here Is the code I am using. I restricted it to those parts that I believe are relevant.
我正在尝试在 Express.js 4 中构建一个上传图像的 Node.js 应用程序。我决定使用该multer
模块,但无法通过req.files
. 这是我正在使用的代码。我将它限制在我认为相关的那些部分。
Jade code:
玉码:
form(method="POST", action="createPost", enctype="multipart/form-data")
input(type="file", name="photo")
br
input(type="submit" value="upload")
in routes/admin.js:
在路由/admin.js 中:
var express = require('express');
var multer = require('multer');
var router = express.Router();
var upload = multer({dest: './uploads/'});
router.post('/createPost', upload.single('photo'), function(req, res, next) {
console.log('files:', req.files);
console.log('body:', req.body);
// more code
}
output:
输出:
files: undefined
body: {}
The file is stored in the uploads
folder but I cannot access its information in req.files
. Can anyone help me?
该文件存储在uploads
文件夹中,但我无法在req.files
. 谁能帮我?
回答by jfriend00
When using upload.single()
, per the multer documentation, the resulting file should be in req.file
, not req.files
. See the example in their doc here.
使用时upload.single()
,每multer文档,生成的文件应该是req.file
,没有req.files
。请参阅此处的文档中的示例。
app.post('/profile', upload.single('avatar'), function (req, res, next) {
// req.file is the `avatar` file
// req.body will hold the text fields, if there were any
})
And, here's the actual doc for upload.single()
:
而且,这是实际的文档upload.single()
:
.single(fieldname)
Accept a single file with the name fieldname. The single file will be stored in req.file.
.single(字段名)
接受名称为 fieldname 的单个文件。单个文件将存储在 req.file 中。