使用multer上传文件时,req.files未定义

arn*_*e.z 13 javascript node.js express 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")
Run Code Online (Sandbox Code Playgroud)

在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
}
Run Code Online (Sandbox Code Playgroud)

输出:

files: undefined
body: {}
Run Code Online (Sandbox Code Playgroud)

该文件存储在uploads文件夹中,但我无法访问其中的信息req.files.谁能帮我?

jfr*_*d00 16

使用时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
})
Run Code Online (Sandbox Code Playgroud)

而且,这是实际的文档upload.single():

.单(字段名)

接受名为fieldname的单个文件.单个文件将存储在req.file中.