为 multer 中的多个字段设置多个大小限制

问题描述 投票:0回答:1

我有一个路由器来处理上传多个图像和视频时的表单提交,我需要设置图像和视频的最大大小限制,multer“限制”属性仅接受一个值,我尝试检查文件内的大小像下面的代码一样进行过滤,但显然在收到文件之前我无法访问文件的大小..

const DIR = './uploads/';

const MAX_IMAGE_SIZE = 2 * 1024 * 1024;
const MAX_VIDEO_SIZE = 100 * 1024 * 1024;

const storage = multer.diskStorage({
    destination: (req, file, cb) => {
        fs.mkdirSync(DIR, { recursive: true });
        cb(null, DIR);
    },
    filename: (req, file, cb) => {
        const fileName = file.originalname.toLowerCase().split(' ').join('-');
        cb(null, uuidv4() + '-' + fileName)
    }
});

let upload = multer({
    storage: storage,
    fileFilter: (req, file, cb) => {
        if (file.fieldname == "images") {
            if (file.size > MAX_IMAGE_SIZE) {
                req.imageValidationError = "Image size can't exceed 2MB";
                return cb(req.fileValidationError);
            }
            if (file.mimetype == "image/png" || file.mimetype == "image/jpg" || file.mimetype == "image/jpeg" || file.mimetype == "image/webp") {
                cb(null, true);
            } else {
                req.imageValidationError = "Unsupported Image Type";
                return cb(req.fileValidationError);
            }
        }
        else if (file.fieldname == "video") {
            if (file.size > MAX_VIDEO_SIZE) {
                req.videoValidationError = "Video size can't exceed 100MB";
                return cb(req.fileValidationError);
            }
            if (file.mimetype == "video/ogg" || file.mimetype == "video/webm" || file.mimetype == "video/mp4" || file.mimetype == "video/ogv") {
                cb(null, true);
            } else {
                req.videoValidationError = "Unsupported video Type";
                return cb(req.fileValidationError);
            }
        }
    }
});

对此我能做什么? 我正在考虑为图像和视频设置单独的“上传”处理程序..但这似乎不是一个干净的方法

node.js express multer
1个回答
0
投票

如果这能解决您的问题,请告诉我。

我的类似,但更复杂。

表达multer如何上传不同类型不同大小的文件

© www.soinside.com 2019 - 2024. All rights reserved.