Express.js & REST APIs
Node.js File Upload with Multer
Multer is Express middleware for multipart/form-data, which is how browsers send files. It handles parsing, storage location, file naming, size limits and type filtering.
What is File Upload with Multer in Node.js?
Multer is Express middleware for multipart/form-data, which is how browsers send files. It handles parsing, storage location, file naming, size limits and type filtering.
File Upload with Multer example
JavaScript
import multer from 'multer';
import path from 'node:path';
import crypto from 'node:crypto';
const upload = multer({
storage: multer.diskStorage({
destination: 'uploads/resumes',
filename: (req, file, cb) => {
// never trust the client filename
const safe = crypto.randomUUID() + path.extname(file.originalname).toLowerCase();
cb(null, safe);
},
}),
limits: { fileSize: 2 * 1024 * 1024 }, // 2 MB
fileFilter: (req, file, cb) => {
const ok = ['application/pdf', 'application/msword'].includes(file.mimetype);
cb(ok ? null : new Error('Only PDF and DOC files are allowed'), ok);
},
});
app.post('/api/apply', upload.single('resume'), (req, res) => {
res.status(201).json({ file: req.file.filename });
});Key points to remember
- upload.single for one file, .array for many, .fields for mixed names.
- Always set a fileSize limit or an upload can fill the disk.
- Generate the stored filename yourself — client names enable path traversal.
- For anything at scale, stream directly to S3 or similar rather than local disk.
Common mistakes with File Upload with Multer
- Using file.originalname as the saved name, allowing "../" traversal and overwrites.
- Trusting the mimetype header, which a client can set freely — check magic bytes for sensitive uses.
- Serving the upload directory statically, so uploaded scripts become executable URLs.
Node.js File Upload with Multer— Interview Questions & FAQs
Why is req.file undefined with Multer?+
The form field name does not match the argument to upload.single(), or the form is not sending multipart/form-data. Both must line up exactly.
