How to limit file size or number of files in multer express and handle error?

Viewed 2080

I am writing a code where I need to limit the file size or limit the number of files uploaded.

For example, a user can upload maximum 100 files at once or user can upload files up to the size of 100 mb. But when I run it and select 7 files of 10 mb each it gives me this error:

enter image description here

Also how can I handle error if any of the limit exceeds when user uploads?

Below is my code:

var maxSize = 100 * 1024 * 1024;
const express = require("express")
const multer = require('multer');
const csvtojson = require('csvtojson');

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
      cb(null, './upload') //Destination folder
    },
    filename: function (req, file, cb) {
      cb(null, file.originalname) //File name after saving
    }
  })
const upload = multer({ storage: storage ,limits: { fileSize: maxSize }});
const router = express.Router()

router.post("/multiple",upload.array("ziptable",100),(req,res)=>{
    var file = req.files;
    console.log(file)
    res.send("ok")
})

my html:

    <form action="/multiple" method="POST" enctype="multipart/form-data">
        <div id="middle">
            <input id="uploadzip" name="ziptable" type="file" multiple>
            <button id="submit" type="submit" class="btn btn-primary">SELECT FILES</button>
        </div>
    </form>
1 Answers

For now, there is no functionality like allFileSizeLimitto handle this issue.

Maybe you can write some custom code in the fileFilter function. Find the sum of the file sizes and if that total size exceeds your limit you can throw an custom error.

In addition, you can write custom form submitter in the frontend javascript and send the request to server only if the total size is lesser than your limit. But this javascript can be changed by the browser console so you have to write the above logic in server.

Related