agyanadda@gmail.com

Node.js File Upload with Multer

Express.js and Databases 1 min read Updated Dec 3, 2026 Topic 23 of 30

Multer is Express middleware for handling multipart/form-data — the format used for file uploads.

Install

npm install multer

Configure storage

  • multer({ dest: 'uploads/' }) — quick: saves with random names and no extension
  • multer.diskStorage({ destination, filename }) — choose the folder and a safe name
  • multer.memoryStorage() — keep the file in memory, e.g. to send to cloud storage

Limits and filters

  • limits: { fileSize: 2 * 1024 * 1024 } — 2 MB
  • fileFilter — accept only allowed MIME types (images, PDF)

Use it on a route

  • upload.single('photo') → req.file
  • upload.array('photos', 5) → req.files
  • Other form fields are in req.body

The HTML form

Needs method="post" and enctype="multipart/form-data". With fetch, send a FormData object.

Serve uploads with express.static('uploads'). For production, cloud storage (S3, Cloudinary) is better than the server's disk.

Example

Example — Image upload with limits JavaScript
import express from 'express';
import multer from 'multer';
import path from 'node:path';
import crypto from 'node:crypto';

const app = express();
app.use('/uploads', express.static('uploads'));

const storage = multer.diskStorage({
  destination: 'uploads/',
  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname).toLowerCase();
    cb(null, crypto.randomUUID() + ext);
  },
});

const upload = multer({
  storage,
  limits: { fileSize: 2 * 1024 * 1024 },
  fileFilter: (req, file, cb) => {
    const ok = ['image/jpeg', 'image/png', 'image/webp'].includes(file.mimetype);
    cb(ok ? null : new Error('Only JPG, PNG or WEBP images are allowed'), ok);
  },
});

app.post('/api/avatar', upload.single('photo'), (req, res) => {
  res.status(201).json({ url: `/uploads/${req.file.filename}`, size: req.file.size });
});

app.use((err, req, res, next) => res.status(400).json({ error: err.message }));
app.listen(3000);

Uploading a 500 KB JPG returns {"url":"/uploads/3f2a...jpg","size":512000}. A PDF or a 5 MB image returns 400 with an error message.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which Multer method accepts one file from the field 'photo'?

Exercise 2 True / False

The upload form needs enctype="multipart/form-data".

Exercise 3 Fill in the Blank

A single uploaded file is available as req.___

Frequently Asked Questions

With multer({ dest }), Multer uses a random name with no extension for safety. Use diskStorage with a filename function (as in the example) to add the extension.