NodeJS Multer validate fields before upload

别说谁变了你拦得住时间么 提交于 2019-12-10 18:29:27

问题


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...
});


来源:https://stackoverflow.com/questions/48173677/nodejs-multer-validate-fields-before-upload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!