2
votes

With my Error Handling, It throws the Error as expected, even though it uploads some files(till reaches the limit) and then the Error is thrown. how to throw this error before uploading some chunk files?

enter image description here

How to throw error before uploading, when it exceeds the limit no of files uploaded? Thanks in advance!

Which I tried:

app.post('/upload',[
multer({
dest    : function(req, file, cb){
let dest = 'uploads/1992-12-11/'
let len = parseInt(req.files.length);
if(len === 20){
console.log('let us throw error');
}
cb(null, dest);
}
onError : function(err, next){
console.log('error' + err);
next(err);
}
}),
function(req, res) {
res.status(204).end();
}
});

Used express-fileupload to validate using multer specified technique

var multer = require('multer')
var upload = multer().single('avatar')

app.post('/profile', function (req, res) {
  upload(req, res, function (err) {
  if (err instanceof multer.MulterError) {
  // A Multer error occurred when uploading.
  } else if (err) {
  // An unknown error occurred when uploading.
  }

   // Everything went fine.
  })
})

which returns null for console.log(req.files);

Tried almost everything in this thread: File uploading with Express 4.0: req.files undefined

Error Handling:

app.post('/upload',[
  multer({
    dest    : './uploads/1992-12-11/',
    onError : function(err, next) {
      console.log('error', err);
      next(err);
    }
 }),
 function(req, res) {
   res.status(204).end();
   }
 ]);
1

1 Answers

3
votes

Since you are uploading multiple files it should be multer array. You can specify the file limit like so:

var upload = multer().array('file', 20); // where 20 is the limit

your route handler can be the same and the error can be handled in if:

app.post('/profile', function (req, res) {
  upload(req, res, function (err) {
  if (err instanceof multer.MulterError) {
  // A Multer error occurred when uploading.
  } else if (err) {
  // An unknown error occurred when uploading.
  }
   // Everything went fine.
  })
})