How to limit the file size when uploading with multer?

扶醉桌前 提交于 2019-12-03 11:24:21

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/34697502/how-to-limit-the-file-size-when-uploading-with-multer

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!