multer 如何在上传文件之前访问多部分表单数据

multer how to access multipart form data before uploading files

我正在尝试处理提交文本字段和上传文件的表单,我正在使用 multer 来处理文件上传并使用 express-validator 来验证其他字段。

对于多部分形式,在使用 multer 解析它之前我无法访问 req.body,这意味着我必须在其他需要 req.body 的中间件之前注册 multer 中间件。 我想知道我是否可以上传文件,只有当表单中的其他字段有效时,有没有办法在不使用 multer 解析的情况下访问 req.body?

多重设置

const multer = require('multer');

const storage = multer.diskStorage({
  destination: path.join(__dirname, `../public/images/games/temp/`),
  filename: (req, file, cb) => {
    if(file.fieldname === "cover") {
      cb(null, `main.jpg`);  
    } else if(file.fieldname === "screenshots") {
        if(!req.count)
          req.count = 1;

        cb(null, `ss-${req.count++}.jpg`);
    }
  }
});

const upload = multer({storage});

路由处理程序

exports.game_create_post = [
  upload.fields([{name: "cover", maxCount: 1}, {name: "screenshots", maxCount: 10}]),

  body("a field").validator(),
  body("a field").validator(),
  body("a field").validator(),

  // other middlewares...
]

这是通常 post 填写表格的方式。我们首先验证输入,如果输入通过验证,我们将处理 req.body。但是,由于您是在服务器上编写代码,因此您使用的是 vanilla-javascript 形式。在这种情况下,您必须传递 enctype='multipart/form-data,这是一种允许文件通过 POST 发送的编码类型。没有这种编码,文件无法通过 post 请求发送。

   <form class="product-form" action="/route>" method="POST" enctype="multipart/form-data"></form>

您可以像这样通过过滤器访问其他字段:

var upload = multer({
    storage: storage,
    fileFilter : (req, file, cb) => { uploadFilter(req, file, cb) },
});

function addComicFilter(req, file, cb) {
    //Here you can access the other fields
    console.log(req.body.title)
    console.log(req.body.description)
    //and you won't get undefined anymore.
    //so do your validation here.
}

app.post('/addComic', upload.single('image'), function (req, res, next) {

 //Can't access other fields through req.body.<Name of the field>
 //You can only access those through the uploadFilter function so your validation
 //should be there.
}