使用 multer 上传文件时的文件大小限制

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

我正在实现一个文件上传器,它接受各种文件类型,包括图像和视频。我需要以不同的方式管理图像和视频的最大文件大小:图像的最大大小应为 10MB,而视频的最大大小应限制为 100MB。我希望使用 Multer 的单个实例来完成此功能,Multer 是一个用于处理多部分/表单数据的中间件。

import path from "path";
import { TEMP_DIRECTORY_PATH } from "../constants.js";
import { ApiError } from "../utils/ApiError.js";

const storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, TEMP_DIRECTORY_PATH);
    },
    filename: function (req, file, cb) {
        const fileName = Date.now() + "-" + Math.round(Math.random() * 1e9);
        const fileExtension = path.extname(file.originalname);
        cb(null, fileName + fileExtension);
    },
});

const fileFilter = (req, file, cb) => {
    const imageMimeTypes = [
        "image/png",
        "image/jpeg",
        "image/webp",
        "image/svg+xml",
    ];
    const videoMimeTypes = ["video/mp4", "video/webm"];

    const allowedMimeTypesForFields = {
        avatar: imageMimeTypes,
        coverImage: imageMimeTypes,
        videoFile: videoMimeTypes,
        thumbnail: imageMimeTypes,
        featuredImage: imageMimeTypes,
    };

    const allowedMimeTypesForField = allowedMimeTypesForFields[file.fieldname];

    if (!allowedMimeTypesForField) {
        return cb(
            new ApiError(
                500,
                `Invalid field ${file.fieldname}. Please ensure you are uploading to a valid field.`
            ),
            false
        );
    }

    if (allowedMimeTypesForField.includes(file.mimetype)) {
        cb(null, true);
    } else {
        cb(
            new ApiError(
                400,
                `Invalid file type for ${file.fieldname}. Allowed file types for ${file.fieldname} are ${allowedMimeTypesForField.map((type) => type.split("/")[1]).join(", ")}.`
            ),
            false
        );
    }
};

export const upload = multer({
    storage,
    fileFilter,
});

是否可以用我给定的代码来做到这一点?或者我必须制作 2 个 multer 实例,一个用于图像,一个用于视频。

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

您不需要

fileFilter
函数,因为我们可以在那里获得
file.size
,这样我们就可以简单地将其转换为中间件。

在 multer 中参考此问题

在中间件中,您可以应用文件大小验证,如下所示。

function FileValidationMiddleware(req,_,next)=>{
    const { file } = req;
    const fileSize = file.size / 1024 / 1024; // in MB
    
    const types = {
        'image': {
            maxSize: 1 ,//MB
            mimetype: [
                "image/png",
                "image/jpeg",
                "image/webp",
                "image/svg+xml",
            ]
        },
        'video': {
            maxSize: 100, //MB
            mimetype: [
                "video/mp4", 
                "video/webm"
            ]
        }
    }

    const allowedMimeTypesForFields = {
        avatar: 'image',
        coverImage: 'image',
        videoFile: 'video',
        thumbnail: 'image',
        featuredImage: 'image',
    };

    const allowedMimeTypesForField = allowedMimeTypesForFields[file.fieldname];

    if (!allowedMimeTypesForField) {
        throw new ApiError(
            500,
            `Invalid field ${file.fieldname}. Please ensure you are uploading to a valid field.`
        );
    }


    if (types[allowedMimeTypesForField].mimetype.includes(file.mimetype)) {
        if(fileSize > types[allowedMimeTypesForField].maxSize){
            throw new ApiError(400,`Invalid file size for ${file.fieldname}. Allowed maximum file size is ${imageMimeTypes.maxSize} MB`);
        }
        next();
    } else {
        throw new ApiError(
            400,
            `Invalid file type for ${file.fieldname}. Allowed file types for ${file.fieldname} are ${allowedMimeTypesForField.map((type) => type.split("/")[1]).join(", ")}.`
        );
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.