Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS- How can I limit file size while using express-fileupload

I am using express-fileupload and its working fine and uploading images . I cant find a way to limit the file size, or write a check in which I make sure no file is uploaded having size more than 1MB.

    app.post('/upload', function(req, res) {
  if (!req.files)
    return res.status(400).send('No files were uploaded.');

  // The name of the input field (i.e. "sampleFile") is used to retrieve the uploaded file
  let sampleFile = req.files.sampleFile;

  // Use the mv() method to place the file somewhere on your server
  sampleFile.mv('/somewhere/on/your/server/filename.jpg', function(err) {
    if (err)
      return res.status(500).send(err);

    res.send('File uploaded!');
  });
});

I tried something like this which is actually clipping the remaining image

    app.use(fileUpload({
    limits: {
        fileSize: 1000000 //1mb
    },
}));

I can do this JavaScript by checking the file size of every file, but is there not any build in feature ??? How about multiple file upload on a single click? for multiple files it will go through the loop and check each file size and exclude those files having size greater than 1mb and upload only those having size meet with requirement. So I am wondering apart from writing my own code is there not any build in features ???

like image 941
Usman Iqbal Avatar asked Oct 27 '25 06:10

Usman Iqbal


2 Answers

It's truncating the remaining image because the size limit was reached and you didn't explicitly set the middleware to abort the upload in this case.

So, try setting the option "abortOnLimit" to true, like this:

 app.use(fileUpload({
    limits: {
        fileSize: 1000000 //1mb
    },
    abortOnLimit: true
 }));

For more information, this is what the documentation tells about using the option 'abortOnLimit':

Returns a HTTP 413 when the file is bigger than the size limit if true. Otherwise, it will add a truncate = true to the resulting file structure.

Source link: https://www.npmjs.com/package/express-fileupload

like image 127
Claudio Augusto Pereira Rolim Avatar answered Oct 28 '25 20:10

Claudio Augusto Pereira Rolim


In express-fileupload, I can see the busboy options. Have you tried that? https://github.com/richardgirges/express-fileupload#using-busboy-options

I wanted to write this in comments but I don't have enough reputation points. :(

like image 26
tumulr Avatar answered Oct 28 '25 18:10

tumulr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!