Node.js Express File Upload
Handle file uploads in Node.js Express using multer middleware with disk and memory storage strategies, file filtering by MIME type, size limits, and.
Code
import multer from 'multer';
const storage = multer.diskStorage({
destination: (req, file, cb) => cb(null, 'uploads/'),
filename: (req, file, cb) => cb(null, `${Date.now()}-${file.originalname}`),
});
const upload = multer({
storage,
limits: { fileSize: 10 * 1024 * 1024 },
fileFilter: (req, file, cb) => {
const allowed = ['image/png', 'image/jpeg', 'application/pdf'];
cb(null, allowed.includes(file.mimetype));
},
});
app.post('/upload', upload.single('file'), (req, res) => {
res.json({ path: req.file.path, size: req.file.size });
});How it works
Top-level bindings storage, upload hold the demo state — nothing sits inside a function scope.
What to watch for
- Requires
multeras a package; the snippet will not run without it.
Key statements
app.post('/upload', upload.single('file'), (req, res) => {
res.json({ path: req.file.path, size: req.file.size });
});
fileFilter: (req, file, cb) => {
const allowed = ['image/png', 'image/jpeg', 'application/pdf'];
cb(null, allowed.includes(file.mimetype));
},
FAQ
- Do I need to install anything before running this?
- Yes: `multer` must be present in the project or the import fails at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.