QA
Intermediate LevelExpress JS

How do you handle multipart/form-data file uploads safely in Express using multer?

❓ Interview Prompt: Explain multer middleware, handling multipart/form-data, destination storage, file size limits, and MIME type fileFilter validation.

By default, Express cannot parse 'multipart/form-data' file upload requests. 'multer' is the standard middleware for processing file uploads.

Security Best Practices:

1
File Size Limits: Set 'limits: { fileSize: 5 1024 1024 }' (5MB limit) to prevent Disk Exhaustion DoS attacks.
2
MIME Type Whitelisting: Validate file types inside 'fileFilter' ('mimetype === "image/png"'). Never rely on file extensions alone!

Code Implementation Example

javascript
import express from 'express';
import multer from 'multer';

const app = express();

const upload = multer({
  dest: 'uploads/',
  limits: { fileSize: 5 * 1024 * 1024 }, // 5MB limit
  fileFilter: (req, file, cb) => {
    if (file.mimetype.startsWith('image/')) {
      cb(null, true);
    } else {
      cb(new Error('Only image files are allowed!'), false);
    }
  }
});

app.post('/api/upload-avatar', upload.single('avatar'), (req, res) => {
  res.json({ file: req.file });
});
💡Handling single file uploads safely with multer size limits and MIME filtering.
🎯 Interview Key Takeaway

Use multer to handle multipart/form-data file uploads, specifying fileSize limits and fileFilter MIME type validation.

#multer#File Uploads#Multipart#Intermediate
Back to all Express JS Questions→

More Express JS Interview Questions

Beginner LevelExpress JS

What is Express.js and how does the middleware pipeline work?

Beginner LevelExpress JS

What is the difference between req.params, req.query, and req.body?

Beginner LevelExpress JS

How does express.Router() work for building modular route controllers?