'How to limit the file size when uploading with multer?

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?



Solution 1:[1]

I think it is you are looking. Have a great day.

const fileFilterMiddleware = (req, file, cb) => {
    const fileSize = parseInt(req.headers["content-length"])

    if ((file.mimetype === "image/png" || file.mimetype === "image/jpg" || file.mimetype === "image/jpeg" || file.mimetype === "application/octet-stream") && fileSize <= 1282810) {
        cb(null, true)
    } else if (file.mimetype === "video/mp4" && fileSize <= 22282810) {
        cb(null, true)
    } else {
        cb(null, false)
    }
}

Solution 2:[2]

For anyone who uses Multer with Ts.ED. When I tried to upload a too large file (no matter what extension it had), I ended up with the following error showing up:

Cannot read properties of undefined (reading 'replace')

I did use the following code to fix this:

@Configuration({
  ...
  multer: {
    limits: {
      fieldNameSize: 300,
      fileSize: 1048576, // 10 Mb
    },
    fileFilter: (req, file, callback) => {
      const acceptableExtensions = ['.png', '.jpg'];
      if (!(acceptableExtensions.includes(Path.extname(file.originalname)))) {
        return callback(new Error('...'));
      }

      // added this
      const fileSize = parseInt(req.headers['content-length']);
      if (fileSize > 1048576) {
        return callback(new Error('...'));
      }
      // --


      callback(null, true);
    }
  }
})

Now it works.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joel Peltonen
Solution 2 mszan