multer: No simple way to tell the client if an error occured

All of the error handling functions, onFileSizeLimit, onError etc… have no way of either telling the client that an error has happened or passing the fact an error happened to the next middle ware:

  router.use('/uploads', multer({
    dest: './uploads',
    limits: { files: 2 },
    onFilesLimit: function () {
      // No way to add to the request that an error occurred, or respond to the client
   }
  });

  router.post('/uploads', function(req, res) {
    // Cannot tell that any of the limits has been reached so cannot inform the client
  });

You probably don’t want to respond to the client directly when a limit has been hit, but you should at least be able to tell that an error occurred later on.

Something along the lines of:

  router.use('/uploads', multer({
    dest: './uploads',
    limits: { files: 2 },
    onFilesLimit: function (file_data) {
      file_data.files_limit_reached = true;
   }
  });

  router.post('/uploads', function(req, res) {
    if (file_data.files_limit_reached) {
        res.json({ error: "file limit reached" });
    }
  });

So that rather then removing the files that have hit an error or exceeded a limit they are flagged with an error message.

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Comments: 18 (6 by maintainers)

Most upvoted comments

hi @qqilihq, I’d like to share my solution. please take a look:

app.use('/route', multer({
  dest: './upload/',
  limits: {
    fileSize: 1024*1024, // at most 1MB
  },
  // setting attributes of `file` is useful for passing info to the
  // next middleware
  onFileSizeLimit: function (file) {
    fs.unlink('./' + file.path); // delete the partially written file
    file.failed = true;
  }
}));

After the middleware above, we can do the trick as below:

app.use('/route', function(req, res, next){
  // take the 1st file for example, of course you can do a for-loop instead
  var files = req.files.yourfilename; // yourfilename is the field name defined in front-end
  var file = files[0];
  if (!file.failed) {
    // gotcha!
  }
}

I think this might help you. One more thing might be helpful: onFileUploadComplete does not mean success, any single file will fire this event one time, even if it runs over filesize limit.

Why has onFileSizeLimit been removed? Is there an alternative to it that we could use?

There isn’t any onFileSizeLimit option any more so that will never log. You other code should work thought, however; I think that you are hitting bug #168.