Unable to handle multer filefilter error

I am playing with file upload in node.js / multer

I got storage and limited work. But now I am playing with a file to just ban some files with mimetype like this:

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

When a file is downloaded, not png, it does not accept it. But it also will not trigger a launchif(err)

When a file is large, it generates an error. So for some reason I need to generate an error on filefilter, but I'm not sure how to guess it new Errorwrong

So, how should I generate an error if the file is incorrect. What am I doing wrong?

Full code:

var maxSize = 1 * 1000 * 1000;

var storage =   multer.diskStorage({
  destination: function (req, file, callback) {
    callback(null, 'public/upload');
  },
  filename: function (req, file, callback) {
    callback(null, file.originalname);
  }
});


var upload = multer({
   storage : storage,
   limits: { fileSize: maxSize },
   fileFilter: function (req, file, cb) {
     if (file.mimetype !== 'image/png') {
       return cb(null, false, new Error('I don\'t have a clue!'));
     }
     cb(null, true);
   }

 }).single('bestand');


router.post('/upload',function(req,res){
    upload(req,res,function(err) {
        if(err) {
              return res.end("some error");
        }
    )}
)}
+7
source share
3 answers

fileFilter (req). .

fileFitler ( , ). , .

:

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

:

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

.

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

    cb(null, true)
  }
})
+1

Change fileFilterand pass the error to the function cb:

function fileFilter(req, file, cb){
   const extension = file.mimetype.split('/')[0];
   if(extension !== 'image/png'){
       return cb(new Error('Something went wrong'), false);
    }
    cb(null, true);
};
+1
source

Source: https://habr.com/ru/post/1626269/


All Articles