File Upload — Node.js

Files are sent in the multipart/form-data format (the form needs that enctype) and read by the multer middleware. upload.single("photo") fills req.file, which…

The easiest way to accept an upload: take the file, save it under its original name in the public/ folder, done. It's also the easiest to attack. One person can send a 2 GB file, an .html file full of script pretending to be a photo, or a file with the same name that overwrites someone else's file.

A file upload means a user sends a file (a photo, a PDF) to your server, and the server stores it. A safe server blocks those three problems (huge files, disguised files and names that clash) with four habits. We add all of them to notes-api: a size limit, a check of the file's content, a random name, and a folder outside public/.

The upload form: multipart/form-data

A JSON body can only carry text. Files travel in another format: multipart/form-data. The HTML form must name that format in its enctype attribute. Without that attribute, only the file's name is sent. Here is a form that attaches a photo to note 1:

<form action="/notes/1/attachments" method="POST" enctype="multipart/form-data">
  <input type="file" name="photo">
  <button>Upload</button>
</form>

The body of the request from that form is split into parts, with the line ------WebKitFormBoundary... between them. The file's part carries the field name, the file name, the type the browser guessed, then the file's content:

------WebKitFormBoundaryq8VnUqfzQn6w2kZ1
Content-Disposition: form-data; name="photo"; filename="photo.jpg"
Content-Type: image/jpeg

(2,202,010 bytes of file content)
------WebKitFormBoundaryq8VnUqfzQn6w2kZ1--

express.json() can't read this format. multer can.

Multer: from the request to req.file

Multer is Express middleware for multipart/form-data. Install it with npm install multer, then use it like this:

const multer = require("multer");

const upload = multer({
  storage: multer.memoryStorage(), // the file's content goes into req.file.buffer
  limits: { fileSize: 5 * 1024 * 1024 }, // 5 MB = 5,242,880 bytes
});

app.post("/notes/:id/attachments", upload.single("photo"), async (req, res) => {
  if (!req.file) {
    return res.status(400).json({ error: "No file in the photo field" });
  }
  // check the type, store it, then answer 201 (next sections)
});

For photo.jpg, req.file holds fieldname: 'photo', originalname: 'photo.jpg', mimetype: 'image/jpeg', size: 2202010 (bytes), and buffer (the file's content as a sequence of bytes). Remember this one: originalname and mimetype are written by the sender. Only size and buffer come from the actual content of the file.

Size limit: 413

With limits.fileSize, multer stops reading as soon as the file passes 5,242,880 bytes, then throws MulterError: File too large with code: "LIMIT_FILE_SIZE". If nothing handles that error, Express answers 500 with an HTML error page. The right answer is 413 Payload Too Large (what was sent is too big). You send it from an error middleware, a middleware with four parameters placed after every route:

app.use((err, req, res, next) => {
  if (err instanceof multer.MulterError && err.code === "LIMIT_FILE_SIZE") {
    return res.status(413).json({ error: "File too large (max 5MB)" });
  }
  next(err); // other errors still go to the built-in handler
});

This is the result when large.jpg (6.2 MB) is sent with curl. -F "[email protected]" sends that file in the field photo, like a form does. -s hides the progress display, and -w prints the status code at the end:

$ curl -s -w "\nHTTP %{http_code}\n" -F "[email protected]" http://localhost:3000/notes/1/attachments
{"error":"File too large (max 5MB)"}
HTTP 413

Without limits, a 2 GB file is accepted too and held in memory. A few uploads like that are enough to use up the server's RAM.

Check the type from the content, not the label

req.file.mimetype is the Content-Type the sender wrote. The browser guesses it from the extension (the end of the file name). So a PDF file receipt.pdf renamed to receipt.jpg arrives as image/jpeg. With curl, anyone can write any type, for example an HTML file labelled image/png: curl -F "[email protected];type=image/png". The extension in originalname comes from the sender too.

Only the content can be trusted. Every file format starts with its own typical bytes, like a signature, and those bytes are called magic bytes. This table writes them in hex (numbers in base 16: the digits 0 to 9 and the letters a to f):

Format First bytes (hex) Read as text
JPEG ff d8 ff (not letters)
PNG 89 50 4e 47 .PNG
WebP 52 49 46 46 .. .. .. .. 57 45 42 50 RIFF....WEBP
PDF 25 50 44 46 %PDF
HTML 3c 68 74 6d 6c <html

The function below reads the magic bytes from buf, the file's content, and returns the extension. If the content isn't JPEG, PNG or WebP, the result is null:

function typeFromContent(buf) {
  if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return "jpg";
  if (buf[0] === 0x89 && buf.toString("ascii", 1, 4) === "PNG") return "png";
  if (buf.toString("ascii", 0, 4) === "RIFF" && buf.toString("ascii", 8, 12) === "WEBP") return "webp";
  return null; // not an image we accept
}

A random name, stored outside public/

Here is the rest of the upload route, after req.file is checked:

const path = require("node:path");
const fs = require("node:fs/promises");
const crypto = require("node:crypto");

const FOLDER = path.join(__dirname, "storage", "attachments"); // not in public/

// inside the handler, after checking req.file:
const ext = typeFromContent(req.file.buffer);
if (!ext) {
  return res.status(415).json({ error: "File type not allowed" });
}
const name = crypto.randomUUID() + "." + ext;
await fs.writeFile(path.join(FOLDER, name), req.file.buffer);
res.status(201).json({ attachment: name, size: req.file.size });

The results of four uploads to this server:

File sent Actual content Answer
photo.jpg, 2.1 MB JPEG 201, stored as 9b2f...8f31.jpg
large.jpg, 6.2 MB JPEG 413 File too large (max 5MB)
receipt.jpg, 184 KB PDF 415 File type not allowed
avatar.html, claiming image/png HTML with a script 415 File type not allowed

How attackers use an upload with weak checks (web shells, path traversal, SVGs with scripts) is covered in the Secure File Upload lesson of the Security track.

In the exercise: validateUpload

In the exercise, the simulator has no multer, so each file is an object { filename, size, mimetype }. Treat mimetype here as the type the server already detected from the content. The checks run in order, the same as on the server above: the file name must exist, a file with file.size > MAX_SIZE is refused, then the type is checked with allowedTypes.includes(file.mimetype). The first two checks are already in the starter, and you write the type check yourself. The function in the starter returns { valid: true, ext, sizeMB } (the extension from path.extname, such as ".jpg") or { valid: false, error }. Print the results for its three files (photo.jpg 2 MB, document.pdf, bigfile.png 10 MB) with JSON.stringify:

{"valid":true,"ext":".jpg","sizeMB":"2MB"}
{"valid":false,"error":"File type not allowed"}
{"valid":false,"error":"File too large (max 5MB)"}

⚠️ Uploads that vanish, fail, or turn dangerous

TL;DR: Files are sent in the multipart/form-data format (the form needs that enctype) and read by the multer middleware. upload.single("photo") fills req.file, which is undefined when no file came, so check it first and answer 400. Set limits: { fileSize: 5 * 1024 * 1024 } (5 MB), then turn the LIMIT_FILE_SIZE error into a 413 answer in an error middleware. mimetype (the file type) and the extension are written by the sender. So decide the type from the magic bytes, the first bytes of the file's content (ff d8 ff JPEG, 89 50 4e 47 PNG, RIFF....WEBP), and refuse the rest with 415. Store the file under a random name from crypto.randomUUID() plus the checked extension, in a folder with no URL such as storage/attachments, not in public/, which anyone can open.

⚡ multer, then check req.file

Write:

app.post("/notes/:id/attachments", upload.single("photo"), async (req, res) => {
  if (!req.file) {
    return res.status(400).json({ error: "No file in the photo field" });
  }
});
Guess first: the user sends the form without picking a file. What does req.file hold?

undefined. A request with no file still reaches the handler, and writing req.file.size right away throws a TypeError. So check it first and answer 400.

Meaning: Files are sent in the multipart/form-data format and read by multer, an Express middleware for uploads. upload is multer with its settings, and upload.single("photo") takes one file from the form field photo into req.file.

⚡ Limit the size

Write:

const upload = multer({
  storage: multer.memoryStorage(),
  limits: { fileSize: 5 * 1024 * 1024 },
});

Meaning: 5 * 1024 * 1024 bytes is 5 MB. A bigger file is refused by multer with the error LIMIT_FILE_SIZE. Turn that error into a 413 answer (what was sent is too big) in an error middleware, a middleware with four parameters. memoryStorage() keeps the file's content in memory.

⚡ Trust the content, not the label

Meaning: mimetype (the file type) and originalname (the file's original name) in req.file are written by the sender. So a PDF file receipt.pdf renamed to receipt.jpg arrives as image/jpeg. Check the type from the first bytes of the file's content (the magic bytes). Then give it a random name with crypto.randomUUID(), and store it outside public/ (the folder whose files anyone can open by URL).

What you will learn