import multer from "multer"; import { diskStorage } from "multer"; import path from 'path'; // Allowed video file extensions const allowedVideoTypes = ['.mp4', '.mov', '.avi', '.temp']; // Filter to check if the file is an image or a video (with specific extensions) const multerFilter = (req, file, cb) => { // Check if the file is an image if (file.mimetype.startsWith("image")) { cb(null, true); } else if (file.mimetype.startsWith("video")) { // Check if the video has a valid extension (.mp4, .mov, .avi) const extname = path.extname(file.originalname).toLowerCase(); if (allowedVideoTypes.includes(extname)) { cb(null, true); } else { cb(new Error("Only .temp, .mp4, .mov, or .avi video files are allowed."), false); // Reject invalid video types } } else { cb(new Error("Please upload only images or videos."), false); // Reject if neither image nor video } }; // Storage settings const storage = diskStorage({ destination: (req, file, cb) => { // Dynamically set the destination folder based on MIME type if (file.mimetype.startsWith("image")) { cb(null, './public/images'); } else if (file.mimetype.startsWith("video")) { cb(null, './public/videos'); } }, filename: (req, file, cb) => { const originalName = path.basename(file.originalname, path.extname(file.originalname)); const customFileName = `${originalName}_${Date.now()}${path.extname(file.originalname)}`; cb(null, customFileName); // E.g., "myImage_1634567890123.jpg" or "videoClip_1634567890123.mp4" } }); const upload = multer({ storage: storage, fileFilter: multerFilter, limits: { fileSize: 1024 * 1024 * 50 // 20MB file size limit } }); // Error handling middleware for multer export const multerErrorHandler = (err, req, res, next) => { if (err instanceof multer.MulterError) { // If the error is related to file size or other Multer error return res.status(400).json({ message: err.message }); } else if (err) { return res.status(400).json({ message: err.message }); } next(); } export default upload;