How to handle file uploads with Multer in Express

· Category: Node.js

Short answer

Add Multer middleware to your Express route. Configure dest or storage to define where files are saved. Access uploaded files via req.file (single) or req.files (multiple) after the middleware runs.

Details

Multer parses multipart/form-data and populates req.body with text fields while handling file streams. You can use diskStorage for direct writes to the filesystem or memoryStorage when forwarding files to cloud storage like S3. Always validate file.mimetype and file.size to prevent malicious uploads.

For large file handling, consider streaming instead of buffering in memory. You may want to read How to stream large files in Node.js for background on efficient data transfer. If you are deploying your upload service in containers, how to use Docker volumes will help you persist uploaded files across container restarts.

Tips

  • Use limits in Multer config to cap file size and prevent DoS.
  • Scan uploaded files with an antivirus service before processing them.
  • Rename files on disk to avoid collisions and directory traversal attacks.
  • For serving uploaded files via CDN, see How to configure CloudFront CDN for static websites.