Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 43 ยท Data and Files

File Uploads

Handle file uploads in Express with multer: multipart forms, size and type limits, disk and S3 storage, safe file names, and a runnable multipart parser.

Profile pictures, CSV imports, PDF attachments: sooner or later your app has to accept files. express.json() cannot help, because files do not travel as JSON. Browsers send them in a multipart/form-data body, a format where the request is split into parts, one per form field or file. Express does not parse it, so you add a package. The standard one is multer.

Uploads are also one of the riskiest features you can build. A user can send huge files, files that lie about their type, or file names designed to overwrite things on your server. This lesson shows the real multer code (read-only here, since npm is not available on this site), the limits you must set, and a runnable stand-in parser so you can see what multipart looks like.

Anatomy of an upload

Multipart body Parts split by a boundary string.
Fields and files Text fields and file parts together.
multer Parses it and fills req.file.
1 / 2

What a multipart request looks like

When a form has enctype="multipart/form-data", the browser picks a random boundary string and sends something like this:

HTTP
POST /avatar HTTP/1.1
Content-Type: multipart/form-data; boundary=----X123

------X123
Content-Disposition: form-data; name="title"

My cat
------X123
Content-Disposition: form-data; name="photo"; filename="cat.txt"
Content-Type: text/plain

meow meow
------X123--

Each part has headers, a blank line and the content. The final boundary ends with two dashes. A parser must read the boundary from the Content-Type header and split on it. Real parsers (multer uses busboy) do this as a stream, so a 500 MB upload never has to sit in memory.

Uploading with multer

JavaScript
import express from 'express';
import multer from 'multer';

const upload = multer({
  dest: 'uploads/',                    // temp folder on disk
  limits: { fileSize: 2 * 1024 * 1024, files: 1 }, // 2 MB, one file
});

const app = express();

app.post('/avatar', upload.single('photo'), (req, res) => {
  // req.file: { originalname, mimetype, size, path, filename }
  // req.body: the text fields, e.g. req.body.title
  res.status(201).json({ saved: req.file.filename, size: req.file.size });
});

app.post('/gallery', upload.array('photos', 5), (req, res) => {
  res.json({ count: req.files.length });
});

upload.single('photo') is middleware: it looks for a file field called photo, writes it somewhere, and exposes req.file. Use upload.array('photos', 5) for several files in one field, and upload.fields([...]) for several different fields. The name in single() must match the name attribute in the HTML form:

HTML
<form action="/avatar" method="post" enctype="multipart/form-data">
  <input type="text" name="title">
  <input type="file" name="photo" accept="image/*">
  <button>Upload</button>
</form>

Forgetting enctype="multipart/form-data" is the number one reason req.file is undefined: without it the browser sends only the file name.

Parsing multipart: a stand-in

Let us build a tiny parser to see what multer does for you. The client uses the standard FormData class (available in Node and in browsers) to produce a real multipart body.

Node.js A tiny multipart parser

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The JSON reply shows a text field and a file part separated cleanly, with the real size of cat.txt (9 bytes). multer gives you the same structure as req.body and req.file. Notice that the client chose the file name, which matters in a moment.

Limits you must set

Without limits, anyone can fill your disk or memory. multer offers these in limits:

Option Protects against
fileSize one gigantic file (bytes)
files thousands of tiny files
fields, fieldSize text field floods
parts total number of parts

When a limit is exceeded, multer passes a MulterError (for example code LIMIT_FILE_SIZE) to the error middleware. Turn it into a proper status:

JavaScript
app.use((err, req, res, next) => {
  if (err instanceof multer.MulterError) {
    const status = err.code === 'LIMIT_FILE_SIZE' ? 413 : 400;
    return res.status(status).json({ error: err.message });
  }
  next(err);
});

Also put limits in front of Express: nginx has client_max_body_size, which rejects oversized requests before they reach Node.

Checking type, naming files, storing them

The Content-Type of a part and its file name come from the client, so they can lie. A file called photo.png may be a script. Defenses, in order of strength: allow-list the types you accept, check the file's first bytes ("magic numbers") for the format you expect, store files outside the web root, and never use the client's file name as a path. Generate your own name and keep the original only as display metadata:

JavaScript
import crypto from 'node:crypto';
import path from 'node:path';

const allowed = new Map([['image/png', '.png'], ['image/jpeg', '.jpg']]);

const storage = multer.diskStorage({
  destination: 'uploads/',
  filename: (req, file, cb) => cb(null, crypto.randomUUID() + allowed.get(file.mimetype)),
});

const upload = multer({
  storage,
  limits: { fileSize: 2 * 1024 * 1024 },
  fileFilter: (req, file, cb) => cb(null, allowed.has(file.mimetype)), // false = skip file
});

The same rules as a runnable check on the stand-in. This one validates the metadata and builds a safe stored name:

Node.js Size limit, type allow list, safe names

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice the last case: the traversal attempt is harmless because the stored name is generated, and path.basename strips folders from the display name. (The random part is masked as xxxxxxxx in the printout so the output is stable.) Statuses: 413 for too large, 415 for an unsupported media type.

Where files go: disk, memory, cloud

  • Disk storage is fine for one server, but the files vanish if the server is replaced, and they do not exist on your other servers.
  • Memory storage (multer.memoryStorage()) puts the file in req.file.buffer. Only use it with a small fileSize limit.
  • Object storage such as Amazon S3 or Cloudflare R2 is the usual production choice. Either upload from your server (multer-s3, or stream the file to the SDK), or, better, have the browser upload straight to the bucket with a short-lived pre-signed URL your API creates. Then big files never touch your servers.

Serve uploaded files from a separate domain or bucket where possible, with Content-Disposition: attachment and X-Content-Type-Options: nosniff, so a hostile HTML or SVG upload cannot run scripts on your site. See Security Best Practices and, for the streams underneath, File Uploads and Multipart.

Scan for viruses if users share files with each other, delete temp files when a request fails, and require authentication before accepting any upload.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is req.file undefined when a form uploads a file?

    Without the multipart encoding the browser sends only the file name as text, so there is nothing for multer to parse.
  2. 2. Which HTTP status fits an upload that exceeds your size limit?

    413 means the request body is larger than the server accepts.
  3. 3. What is the safest way to name a stored upload?

    The client controls originalname, so it can contain path tricks or collide with other files. Keep it only as display metadata.
  4. 4. Why can the mimetype of an upload not be trusted alone?

    The client declares the type. Combine an allow list with checks on the file's actual bytes.

Summary

  • Files arrive as multipart/form-data, which express.json() does not parse; use multer.
  • upload.single, array and fields fill req.file, req.files and req.body.
  • Always set limits (size, count), and answer failures with 413 or 400 through your error handler.
  • Name, type and size come from the client: allow-list types, check bytes and generate your own file names.
  • Prefer object storage and pre-signed URLs in production; serve files with safe headers.

Next: Real-Time Features: SSE and WebSockets.