shash7 shash7 - 1 month ago 25
Node.js Question

Multer | Stop file upload

I am using expressjs 4.0 along with multer to handle file uploads.

Problem is, I want to stop file upload when the file's size exceeds a maxSize variable. But
multer uploads file anyways.

Is there a way to stop this behaviour.

Some example code :

app.post('/upload', function(req, res) {

var maxSize = 32 * 1000 * 1000 // 32mb max

if(req.files.file.length > maxSize) {
// stop upload
} else {
// continue
res.send(201);
}
});

Answer

According to Multer documentation: (https://www.npmjs.org/package/multer) you could use onFileUploadStart(file), and return false if the size is above your limit.

For example:

var express = require('express');
var multer  = require('multer');

var maxSize = 32 * 1000 * 1000;

var app = express();
app.use(multer({
  dest: './uploads/',
  onFileUploadStart: function(file, req, res){
    if(req.files.file.length > maxSize) {
      return false;
    }
  })
}));
Comments