I am accepting file of different types such as images and videos. I want to handle different sizes for image and video type. I want images of max size 10mb and videos of 100mb. I want to achieve this functionality with one multer instance.
import multer from "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,
});
Is it possible to do this with my given code. Or I have to make 2 multer instances one for image and one for video.