Consider this Express middleware snippet that validates uploaded file types:
const multer = require('multer');
const upload = multer({
fileFilter: (req, file, cb) => {
if (file.mimetype === 'image/png' || file.mimetype === 'image/jpeg') {
cb(null, true);
} else {
cb(new Error('Only PNG and JPEG allowed'));
}
}
});If a user uploads a file named notes.txt, what will happen?
Check the fileFilter function and what happens when the mimetype is not allowed.
The fileFilter checks the mimetype. Since 'text/plain' is not 'image/png' or 'image/jpeg', it calls cb(new Error(...)), which rejects the upload with that error message.
Choose the correct fileFilter function to accept only PDF files.
Check the exact mimetype string and how errors are handled.
Option C correctly checks for 'application/pdf' mimetype and rejects with an error if not matched. Option C silently rejects without error, C uses wrong mimetype string, D uses wrong property 'file.type'.
Look at this fileFilter function:
fileFilter: (req, file, cb) => {
if (file.mimetype === 'image/png' || 'image/jpeg') {
cb(null, true);
} else {
cb(new Error('Invalid file type'));
}
}Why does it accept all files, even non-images?
Look carefully at the condition inside the if statement.
The condition file.mimetype === 'image/png' || 'image/jpeg' always returns true because 'image/jpeg' is a truthy string. The correct condition should be file.mimetype === 'image/png' || file.mimetype === 'image/jpeg'.
Given this Express route using multer:
const upload = multer({
fileFilter: (req, file, cb) => {
if (file.mimetype === 'image/png') cb(null, true);
else cb(new Error('Only PNG allowed'));
}
});
app.post('/upload', upload.single('photo'), (req, res) => {
res.json(req.file);
});If a user uploads a valid PNG file named pic.png, what will req.file contain?
Think about what multer does when the file passes the filter.
When the file passes the filter, multer processes it and attaches an object with file info to req.file. This includes properties like originalname, mimetype, and buffer if using memory storage.
To protect your Express app from dangerous file uploads, which approach is most effective?
Think about both file type validation and security scanning.
Checking mimetype in fileFilter helps block unwanted types early. Scanning file content for malware adds security. Relying only on extensions or client-side checks is unsafe. Renaming files doesn't remove harmful content.