How would you validate and restrict uploaded file types and sizes using multer to prevent malicious or oversized uploads?
Short answer
multer accepts a 'fileFilter' function to reject files based on their reported MIME type or extension before they're even fully processed, and a 'limits' option to cap the maximum file size, preventing a malicious or careless client from uploading an unexpectedly huge file or a…
Advertisement
AModel answer
multer accepts a 'fileFilter' function to reject files based on their reported MIME type or extension before they're even fully processed, and a 'limits' option to cap the maximum file size, preventing a malicious or careless client from uploading an unexpectedly huge file or a disallowed file type (like an executable disguised with an image extension).
const upload = multer({
limits: { fileSize: 5 * 1024 * 1024 }, // 5MB max
fileFilter: (req, file, cb) => {
const allowedTypes = ['image/jpeg', 'image/png'];
if (!allowedTypes.includes(file.mimetype)) return cb(new Error('Invalid file type'));
cb(null, true);
},
});Real-world example
An image-upload API rejects any file over 5MB or that isn't a JPEG or PNG at the multer middleware level, preventing wasted bandwidth and storage from oversized or inappropriate file types before the request even reaches the actual route handler logic.
Likely follow-ups
- Why is relying solely on the client-reported MIME type insufficient for genuinely verifying a file's actual content type?
- How would you additionally verify a file's real type by inspecting its actual binary content (magic bytes) rather than trusting the reported MIME type?
Related topics