简体   繁体   中英

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 ???

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. :(

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM