Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 43 ยท Projects

Project: File Upload and Download Service

Build a file service: upload size limits, safe file names, metadata, streaming downloads with correct headers. Real multer code is read-only; a runnable stand-in is included.

Files are where web apps get dangerous. A user-supplied name can try to escape your folder, a huge upload can fill your disk, a wrong content type can turn a download into an attack, and a big file loaded fully into memory can crash the process. In this project you build a small file service that handles all four properly: upload with limits, safe naming, metadata, and a streaming download.

Real Express uses the multer package for multipart uploads (File Uploads). It cannot be installed here, so that code is read-only. The runnable stand-in uploads the raw file bytes in the request body with the original name in a header. That sidesteps multipart parsing but keeps everything that matters: limits, name sanitizing, metadata, headers and streaming. Files live in memory so the demo needs no disk.

The service

POST /files Upload bytes, get metadata back.
GET /files List stored files.
GET /files/:id Stream the file as a download.
1 / 2

Never trust the file name

A client chooses the name it sends. Real uploads have included ../../etc/passwd, C:\Windows\system32\x.dll, names with control characters, extremely long names and .htaccess. If you join that name onto your upload folder, you may write outside it (a path traversal attack) or overwrite something important.

The safest rule: never use the client's name as the storage name. Generate your own (a random id), keep the original only as display metadata, and sanitize it before showing or using it in headers:

JavaScript
import path from 'node:path';

export function safeName(original) {
  const base = path.basename(String(original).replaceAll('\\', '/'));   // drop any directories
  const cleaned = base
    .normalize('NFKC')
    .replace(/[^\w.\- ]+/g, '_')   // keep letters, digits, _ . - and spaces
    .replace(/^\.+/, '')           // no leading dots (hidden files, "..")
    .trim()
    .slice(0, 100);
  return cleaned === '' ? 'file' : cleaned;
}

The first step handles backslashes, because a Windows client may send C:\dir\x.txt, which POSIX basename would treat as one name. Test a hostile list, as the first runnable example does.

Node.js Sanitizing hostile file 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.

Directories vanish, leading dots are removed (so .. and .htaccess become harmless), odd characters turn into underscores, and an empty result falls back to file. Because the sanitized name is only a label, even a mistake here cannot reach the file system.

Real Express version (read-only)

With multer, the upload route looks like this. Multer streams the multipart body to disk and enforces limits for you.

JavaScript
import express from 'express';
import multer from 'multer';
import { randomUUID } from 'node:crypto';
import { createReadStream } from 'node:fs';
import { stat } from 'node:fs/promises';
import path from 'node:path';
import mime from 'mime-types';

const UPLOAD_DIR = path.resolve('uploads');
const ALLOWED = new Set(['image/png', 'image/jpeg', 'application/pdf', 'text/plain']);

const upload = multer({
  storage: multer.diskStorage({
    destination: UPLOAD_DIR,
    filename: (req, file, cb) => cb(null, randomUUID()),   // our own name
  }),
  limits: { fileSize: 2 * 1024 * 1024, files: 1 },
  fileFilter: (req, file, cb) => cb(null, ALLOWED.has(file.mimetype)),
});

const app = express();
const files = new Map();   // id -> metadata (a database in real life)

app.post('/files', upload.single('file'), (req, res) => {
  if (!req.file) return res.status(415).json({ error: 'Missing file or unsupported type' });
  const meta = {
    id: req.file.filename,
    name: safeName(req.file.originalname),
    type: req.file.mimetype,
    size: req.file.size,
  };
  files.set(meta.id, meta);
  res.status(201).json(meta);
});

app.get('/files/:id', async (req, res) => {
  const meta = files.get(req.params.id);
  if (!meta) return res.status(404).json({ error: 'No such file' });
  const filePath = path.join(UPLOAD_DIR, meta.id);     // id came from us, not the client
  res.set({
    'Content-Type': meta.type,
    'Content-Length': String(meta.size),
    'X-Content-Type-Options': 'nosniff',
  });
  res.attachment(meta.name);                            // sets Content-Disposition
  createReadStream(filePath).pipe(res);
});

Multer reports a too-large file as an error with code: 'LIMIT_FILE_SIZE'; map it to 413 Payload Too Large in your error handler. In production prefer pipeline(createReadStream(...), res) so errors and closed connections clean up the stream, or simply res.download(filePath, meta.name), which does it for you (Static Files, Downloads and Streaming).

Also remember that the mimetype multer reports is what the client claims. For stricter checking, look at the file's first bytes (magic numbers) with a library, and never serve user uploads from your main domain if they can be HTML or SVG.

Headers that make downloads safe

  • Content-Type: store the type you decided when the file was accepted, not one derived from the name at download time.
  • Content-Disposition: attachment; filename="report.pdf" asks the browser to save the file instead of displaying it. res.attachment() and res.download() set it for you. Use inline only for types you trust, such as plain images.
  • X-Content-Type-Options: nosniff stops browsers from guessing a different (executable) type.
  • Content-Length lets the client show progress; with a stream you can only set it when you know the size up front.

Runnable stand-in: upload with limits, stream out

The stand-in takes the raw bytes as the request body. The name arrives in an x-filename header, and the declared size is checked before any data is read. It also counts bytes while reading, because the Content-Length header can be wrong or missing. Downloads use pipeline with a readable stream.

Node.js Uploads with limits, metadata and streaming downloads

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.

Follow each upload: the plain text file is stored (201) with its metadata, the traversal name is stored under a harmless display name (the stored id f002 never depends on it), the executable type gets 415, the oversize body gets 413 and the empty body 422. The download carries all the headers from the previous section, and an unknown id is a 404.

An empty body is worth rejecting on purpose: with multipart uploads, a form submitted without choosing a file often arrives as exactly this edge case.

Large files and range requests

Our stand-in loads whole files in memory, which is fine for a lesson but not for videos. With real files on disk, use streams for both directions, so memory use stays flat regardless of file size. For downloads, res.sendFile and res.download (and express.static) already support range requests (Range: bytes=0-999), which let browsers resume downloads and seek in media. If you stream by hand, you have to implement the 206 Partial Content response and its Content-Range header yourself.

For very large uploads, consider direct-to-storage uploads: your API signs a short-lived URL, the client sends the bytes straight to object storage such as S3, and your server only records the metadata. That keeps big transfers off your Node process entirely.

Hardening checklist

  • Enforce limits at three layers: reverse proxy (client_max_body_size in nginx), multer limits, and your own checks.
  • Store files outside the web root and serve them only through your routes, with authorization checks per file.
  • Use random storage names and keep original names as metadata only.
  • Restrict allowed types by allowlist; check magic bytes for sensitive cases.
  • Scan for malware if users share files with each other, and delete orphaned files on a schedule.
  • Rate-limit uploads per user, and set quotas.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why should you not use the client's file name as the storage path?

    A crafted name can traverse directories or overwrite files. Generate your own storage name and keep the original only as sanitized metadata.
  2. 2. Which status code fits an upload that exceeds the size limit?

    413 Payload Too Large tells the client that the request body is bigger than the server accepts.
  3. 3. What does Content-Disposition set to attachment do?

    attachment (with a filename) makes browsers download the file, which prevents uploaded HTML from running as a page on your domain.
  4. 4. Why does the service count bytes while reading the body, not only check Content-Length?

    The declared length is only a claim. Counting the bytes actually received enforces the limit even for dishonest or chunked requests.

Summary

  • Never trust client file names: generate storage names and sanitize display names.
  • Reject oversize uploads early (413), by header and by counting streamed bytes.
  • Allowlist types and store the accepted type with the metadata.
  • Serve downloads with Content-Type, Content-Disposition: attachment and nosniff.
  • Stream files instead of loading them in memory; use res.download or pipeline.
  • Real projects use multer (and often object storage); the stand-in keeps the same limits and headers.

Next: Exercises with Solutions.