How to Validate File Type in Express: Simple Guide
To validate file type in
Express, use middleware like multer with a fileFilter function that checks the file's MIME type or extension before saving. This prevents unwanted file types from being uploaded to your server.Syntax
Use multer middleware with a fileFilter option to validate file types. The fileFilter is a function that receives the request, file, and a callback. You call the callback with null, true to accept the file or null, false to reject it.
req: The Express request object.file: The uploaded file object containingmimetypeandoriginalname.cb: Callback to accept or reject the file.
javascript
const multer = require('multer'); const upload = multer({ storage: multer.memoryStorage(), fileFilter: (req, file, cb) => { if (file.mimetype === 'image/png' || file.mimetype === 'image/jpeg') { cb(null, true); // Accept file } else { cb(null, false); // Reject file } } });
Example
This example shows an Express server that accepts only PNG and JPEG image uploads using multer. If the file type is invalid, the upload is rejected and a message is sent.
javascript
const express = require('express'); const multer = require('multer'); const app = express(); const upload = multer({ storage: multer.memoryStorage(), fileFilter: (req, file, cb) => { const allowedTypes = ['image/png', 'image/jpeg']; if (allowedTypes.includes(file.mimetype)) { cb(null, true); } else { cb(null, false); } } }); app.post('/upload', upload.single('photo'), (req, res) => { if (!req.file) { return res.status(400).send('Invalid file type. Only PNG and JPEG are allowed.'); } res.send('File uploaded successfully.'); }); app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Output
Server running on http://localhost:3000
// On valid file upload: "File uploaded successfully."
// On invalid file upload: "Invalid file type. Only PNG and JPEG are allowed."
Common Pitfalls
- Not checking
file.mimetypeor relying only on file extension can allow unsafe files. - Forgetting to handle the case when
fileFilterrejects a file causes silent failures. - Using disk storage without validation can save unwanted files before checking.
- Not sending a response when file is rejected leads to hanging requests.
javascript
const uploadWrong = multer({ storage: multer.diskStorage({ destination: './uploads', filename: (req, file, cb) => cb(null, file.originalname) }) // Missing fileFilter means no validation }); // Correct way includes fileFilter to reject unwanted files before saving
Quick Reference
- Use
multermiddleware for file uploads in Express. - Implement
fileFilterto checkfile.mimetypeorfile.originalnameextension. - Call
cb(null, true)to accept orcb(null, false)to reject files. - Respond properly when files are rejected to inform users.
Key Takeaways
Use multer's fileFilter option to validate file types before saving.
Check file.mimetype for reliable file type validation.
Reject unwanted files by calling the callback with false in fileFilter.
Always handle rejected files by sending a clear response to the client.
Avoid saving files before validation to prevent storing unsafe files.