NodeJS Multer validate fields before upload

2019-07-10 10:07发布

问题:

I'm trying to validation my form before i upload images but i getting empty string on my middleware

const upload = multer({
  storage: storage
});

router.post('/upload', formsValidation, upload.fields([{

  name: 'images',
  maxCount: 20

}, {

  name: 'imageMain',
  maxCount: 1

}]), function(req, res, next) {
  code...

});

heres my middleware:

function formsValidation (req, res, next) {

  console.log(req.body) //getting empty array here
  return next();
}

i know that i can use fileFilter from multer but some times i dont have any images to upload just string to store and validate, i have tried to parse the req.body from multipart/form-data to string then validate and use next() but i get a range error, any ideia how can i solve this?

回答1:

This is from Multer's docs:

Note that req.body might not have been fully populated yet. It depends on the order that the client transmits fields and files to the server.

That's mean you have to call formsValidation just after multer midlleware, to make sure that all posted data have been fully populated

router.post('/upload', upload.fields([{

    name: 'images',
    maxCount: 20

}, {

    name: 'imageMain',
    maxCount: 1

}]), formsValidation, function(req, res, next) {
    code...
});