简体   繁体   English

如何限制multer express中的文件大小或文件数量并处理错误?

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

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.例如,用户一次最多可以上传 100 个文件,或者用户最多可以上传 100 mb 的文件。 But when I run it and select 7 files of 10 mb each it gives me this error:但是当我运行它并选择 7 个 10 mb 的文件时,它给了我这个错误:

在此处输入图片说明

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:我的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>

For now, there is no functionality like allFileSizeLimit to handle this issue.目前,没有像allFileSizeLimit这样的功能来处理这个问题。

Maybe you can write some custom code in the fileFilter function.也许您可以在fileFilter函数中编写一些自定义代码。 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.此外,您可以在前端 javascript 中编写自定义表单提交程序,并仅在总大小小于您的限制时将请求发送到服务器。 But this javascript can be changed by the browser console so you have to write the above logic in server.但是这个 javascript 可以通过浏览器控制台更改,因此您必须在 server.xml 中编写上述逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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