Consider this Multer setup in an Express app:
const multer = require('multer');
const upload = multer({
limits: { fileSize: 1000 }
});
app.post('/upload', upload.single('file'), (req, res) => {
res.send('File uploaded');
});What will happen if a user uploads a file of 2000 bytes?
const multer = require('multer'); const upload = multer({ limits: { fileSize: 1000 } }); app.post('/upload', upload.single('file'), (req, res) => { res.send('File uploaded'); });
Think about how Multer handles file size limits and errors.
Multer enforces the file size limit and throws a 'LIMIT_FILE_SIZE' error if exceeded. The upload is rejected and the route handler is not called.
Choose the correct Multer configuration to save uploaded files to the 'uploads/' directory with original filenames.
Remember that destination can be a function or a string, but filename must be a function.
Option A correctly uses diskStorage with destination as a string (valid) and filename callback to save files with original names in 'uploads/'. Option A saves files with random names. Option A also works but uses a function for destination. Option A stores files in memory, not disk.
Review this Multer setup:
const multer = require('multer');
const storage = multer.diskStorage({
destination: 'uploads/',
filename: (req, file, cb) => {
cb(null, file.originalname);
}
});
const upload = multer({ storage });Files are not saved to disk after upload. What is the cause?
const multer = require('multer'); const storage = multer.diskStorage({ destination: 'uploads/', filename: (req, file, cb) => { cb(null, file.originalname); } }); const upload = multer({ storage });
Multer requires the destination directory to exist beforehand.
Multer does not create the 'uploads/' folder automatically. If the directory does not exist, the file save operation fails and no file is written to disk.
Given this route:
const upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('avatar'), (req, res) => {
res.json(req.file);
});A user uploads a file named 'photo.png'. What does req.file contain?
const upload = multer({ dest: 'uploads/' });
app.post('/upload', upload.single('avatar'), (req, res) => {
res.json(req.file);
});Check what multer.single adds to the request object.
Multer adds a 'file' object with details about the uploaded file, including originalname, filename (random), path, size, and mimetype.
You want to accept only image files (jpeg, png) in your upload route. Which Multer option helps reject other file types before saving?
Think about how to reject files based on type before saving.
The 'fileFilter' option lets you check the file's mimetype and accept or reject it by calling the callback accordingly. This prevents unwanted files from being saved.