Script Valley
Express.js: APIs and Middleware
Advanced Middleware PatternsLesson 5.3

How to handle file uploads in Express with Multer

multer package, diskStorage, memoryStorage, upload.single, upload.array, file size limits, file type filtering, req.file, req.files, MIME type check

File Uploads with Multer

Multer is the standard Express middleware for handling multipart/form-data โ€” the encoding used for file uploads.

npm install multer

Single file upload with validation

const multer = require('multer');
const path = require('path');

const storage = multer.diskStorage({
  destination: (req, file, cb) => cb(null, 'uploads/'),
  filename: (req, file, cb) => {
    const uniqueName = `${Date.now()}-${Math.round(Math.random()*1e9)}${path.extname(file.originalname)}`;
    cb(null, uniqueName);
  }
});

const fileFilter = (req, file, cb) => {
  const allowed = ['image/jpeg', 'image/png', 'image/webp'];
  if (allowed.includes(file.mimetype)) cb(null, true);
  else cb(new Error('Only JPEG, PNG and WebP allowed'), false);
};

const upload = multer({
  storage,
  limits: { fileSize: 5 * 1024 * 1024 }, // 5MB
  fileFilter
});

app.post('/upload', upload.single('avatar'), (req, res) => {
  if (!req.file) return res.status(400).json({ error: 'No file uploaded' });
  res.json({
    filename: req.file.filename,
    path: `/uploads/${req.file.filename}`,
    size: req.file.size
  });
});

// Multiple files
app.post('/gallery', upload.array('images', 10), (req, res) => {
  res.json({ files: req.files.map(f => f.filename) });
});

Serve the uploads directory statically: app.use('/uploads', express.static('uploads')). Always validate MIME type โ€” never trust the file extension alone.

Up next

Response caching middleware โ€” how to cache API responses

Sign in to track progress

How to handle file uploads in Express with Multer โ€” Advanced Middleware Patterns โ€” Express.js: APIs and Middleware โ€” Script Valley โ€” Script Valley