🚀 Express.js Intermediate

How do you implement file uploads in Express.js?

Answer

Use the multer middleware for handling multipart/form-data file uploads. Install: npm install multer. Configure: const upload = multer({ dest: 'uploads/', limits: { fileSize: 5 * 1024 * 1024 } });. Apply to a route: app.post('/upload', upload.single('avatar'), (req, res) => { res.json({ file: req.file }); });. req.file contains metadata (originalname, mimetype, path, size). Validate file types with Multer's fileFilter option. For production, store files in cloud storage (AWS S3, Cloudinary) rather than the local filesystem — use the multer-s3 storage engine. Always validate file types and sizes to prevent malicious uploads.