req.files 在使用 multer 上传文件时未定义
req.files is undefined when uploading file with multer
我正在尝试在 Express.js 4 中构建一个上传图像的 Node.js 应用程序。我决定使用 multer
模块,但无法通过 req.files
访问上传的文件。
这是我正在使用的代码。我将其限制在我认为相关的部分。
玉码:
form(method="POST", action="createPost", enctype="multipart/form-data")
input(type="file", name="photo")
br
input(type="submit" value="upload")
在routes/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
}
输出:
files: undefined
body: {}
文件存储在 uploads
文件夹中,但我无法在 req.files
中访问其信息。谁能帮帮我?
根据 multer 文档,使用 upload.single()
时,生成的文件应位于 req.file
,而不是 req.files
。请参阅示例 in their doc here。
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
})
而且,这是 upload.single()
的实际文档:
.single(fieldname)
Accept a single file with the name fieldname. The single file will be
stored in req.file.
我正在尝试在 Express.js 4 中构建一个上传图像的 Node.js 应用程序。我决定使用 multer
模块,但无法通过 req.files
访问上传的文件。
这是我正在使用的代码。我将其限制在我认为相关的部分。
玉码:
form(method="POST", action="createPost", enctype="multipart/form-data")
input(type="file", name="photo")
br
input(type="submit" value="upload")
在routes/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
}
输出:
files: undefined
body: {}
文件存储在 uploads
文件夹中,但我无法在 req.files
中访问其信息。谁能帮帮我?
根据 multer 文档,使用 upload.single()
时,生成的文件应位于 req.file
,而不是 req.files
。请参阅示例 in their doc here。
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
})
而且,这是 upload.single()
的实际文档:
.single(fieldname)
Accept a single file with the name fieldname. The single file will be stored in req.file.