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.
Previous
What is express-session and how does session-based auth work?
Next
What is compression middleware in Express and when should you use it?
More Express.js Questions
View all →- Intermediate How do you implement JWT authentication in Express.js?
- Intermediate What is Express middleware chaining and how does it work?
- Intermediate What is the helmet package and why should you use it?
- Intermediate How do you implement rate limiting in Express.js?
- Intermediate What is input validation and how do you do it in Express?