Can't get multer filefilter error handling to work Can't get multer filefilter error handling to work express express

Can't get multer filefilter error handling to work


fileFilter function has access to request object (req). This object is also available in your router.

Therefore in fileFitler you can add property with validation error or validation error list (you can upload many files, and some of them could pass).And in router you check if property with errors exists.

in filter:

fileFilter: function (req, file, cb) { if (file.mimetype !== 'image/png') {  req.fileValidationError = 'goes wrong on the mimetype';  return cb(null, false, new Error('goes wrong on the mimetype')); } cb(null, true);}

in router:

router.post('/upload',function(req,res){    upload(req,res,function(err) {        if(req.fileValidationError) {              return res.end(req.fileValidationError);        }    )})}


You can pass the error as the first parameter.

multer({  fileFilter: function (req, file, cb) {    if (path.extname(file.originalname) !== '.pdf') {      return cb(new Error('Only pdfs are allowed'))    }    cb(null, true)  }})


Change the fileFilter and pass an error to the cb function:

function fileFilter(req, file, cb){   if(file.mimetype !== 'image/png'){       return cb(new Error('Something went wrong'), false);    }    cb(null, true);};