How to limit the file size when uploading with multer?

Merijn de Klerk picture Merijn de Klerk · Jan 9, 2016 · Viewed 34k times · Source

I'm making a simple file upload system with multer:

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);
  },
  onFileUploadStart: function(file, req, res){
    if(req.files.file.length > maxSize) {
      return false;
    }
  }

});

var upload = multer({ storage : storage}).single('bestand');

router.post('/upload',function(req,res){
    upload(req,res,function(err) {
        if(err) {
            return res.end("Error uploading file.");
        }
        console.log(req.file);
        res.redirect(req.baseUrl);
    });
});

This all works fine and the file gets uploaded. The only thing that is not working is the limit on the max size. I made it so that onfileupload start the size of the file gets checked and if its to big it will return false. But the file still just gets uploaded.

It seems that onFileUploadStart isn't doing anything at all. I tried to console.log something in it, but nothing.

What am I doing wrong? How can I limit the file size when uploading with multer?

Answer

mscdex picture mscdex · Jan 9, 2016

There is no onFileUploadStart with the new multer API. If you want to limit the file size, you should instead add limits: { fileSize: maxSize } to the object passed to multer():

var upload = multer({
  storage: storage,
  limits: { fileSize: maxSize }
}).single('bestand');