Consider this Express route using multer middleware for single file upload:
const express = require('express');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
const app = express();
app.post('/upload', upload.single('file'), (req, res) => {
res.send(req.file.originalname);
});If a client uploads a file named photo.png under the form field file, what will the server respond with?
const express = require('express'); const multer = require('multer'); const upload = multer({ dest: 'uploads/' }); const app = express(); app.post('/upload', upload.single('file'), (req, res) => { res.send(req.file.originalname); });
Look at what req.file.originalname represents in multer.
The multer middleware adds a file object to req when using upload.single('file'). The originalname property contains the original name of the uploaded file from the client. So the server responds with 'photo.png'.
Choose the correct code snippet to configure multer for handling a single file upload with field name avatar:
Remember the method to handle a single file upload requires the field name as an argument.
upload.single('avatar') is the correct method to handle a single file upload with the field name 'avatar'. Other methods like array or fields are for multiple files or multiple fields.
Examine this code snippet:
const express = require('express');
const multer = require('multer');
const upload = multer({ dest: 'uploads/' });
const app = express();
app.post('/upload', (req, res) => {
console.log(req.file);
res.send('Done');
});When a file is uploaded, req.file is undefined. Why?
const express = require('express'); const multer = require('multer'); const upload = multer({ dest: 'uploads/' }); const app = express(); app.post('/upload', (req, res) => { console.log(req.file); res.send('Done'); });
Check if the middleware that processes the file is applied to the route.
The multer middleware must be used in the route handler to process the file and populate req.file. Without upload.single('fieldname') or similar middleware, req.file remains undefined.
Given this Express route:
app.post('/upload', upload.single('document'), (req, res) => {
res.json(req.file);
});If a user uploads a file named report.pdf, what key will NOT be present in req.file?
app.post('/upload', upload.single('document'), (req, res) => { res.json(req.file); });
Consider multer's default storage when using dest option.
When multer is configured with dest, it stores files on disk and req.file contains file info like originalname, filename, and path. The buffer property is only present if using memory storage.
In Express, why must upload.single('file') be used as middleware before the route handler function?
Think about what happens to the request data before your route code runs.
Multer middleware processes the multipart/form-data request, extracts the file, and adds it to req.file. This must happen before the route handler accesses req.file. Otherwise, the handler sees undefined.