File uploads

Topic 1 of 3 in Beyond request–response8 min readIntermediateFree course

Overview

Profile photos, documents, CSV imports, assignment submissions — most apps need to accept files. Uploads are also one of the riskiest features you can build: they let strangers put arbitrary bytes onto your systems. Done carelessly, they enable denial of service (huge files), malware hosting, overwriting other files, and even running code on your server.

This topic shows how to accept files safely, and where to store them.

How browsers send files

A JSON body can’t carry binary files efficiently. Browsers use multipart/form-data: the body is split into parts, one per form field, each with its own headers:

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

From JavaScript:

JavaScript
const body = new FormData();
body.append('avatar', fileInput.files[0]);
await fetch('/me/avatar', { method: 'PUT', body }); // the browser sets the Content-Type

express.json() ignores multipart bodies, so you need a parser for them. multer is the standard choice for Express.

Terminal
npm install multer

Receiving a file with multer

JavaScript
import multer from 'multer';

const upload = multer({
  storage: multer.memoryStorage(),           // keep the file in a Buffer (fine for small files)
  limits: {
    fileSize: 5 * 1024 * 1024,               // 5 MB
    files: 1,                                // at most one file
    fields: 10,                              // and a few text fields
  },
});

app.post('/documents', requireLogin, upload.single('document'), async (req, res) => {
  console.log(req.file);
  // {
  //   fieldname: 'document', originalname: 'report.pdf', mimetype: 'application/pdf',
  //   size: 183245, buffer: <Buffer 25 50 44 46 …>
  // }
  console.log(req.body); // other text fields from the form
  // …validate and store
});

Other options: upload.array('photos', 5) for several files in one field, upload.fields([...]) for several fields, and multer.diskStorage({...}) to stream large files to a temporary folder instead of memory.

Limit errors

When a limit is exceeded, multer passes a MulterError to your error handler. Turn it into a proper status code:

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

Never trust what the client says

Everything about an upload comes from the client and can be faked:

Field Can be faked? What to do
originalname (cat.jpg) yes — could be ../../app.js or invoice.pdf.exe never use it as a path; store your own name
mimetype (image/jpeg) yes — it’s just a header check the actual bytes
size enforced by multer’s limits set limits

Check the content. Most file formats start with a recognisable signature (“magic number”):

JavaScript
function detectImage(buf) {
  if (buf.subarray(0, 3).equals(Buffer.from([0xff, 0xd8, 0xff]))) return 'jpg';
  if (buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return 'png';
  if (buf.toString('latin1', 0, 4) === 'RIFF' && buf.toString('latin1', 8, 12) === 'WEBP') return 'webp';
  return null;
}

The file-type package detects hundreds of formats this way. For images, re-encoding them with a library such as sharp (resizing as you go) is an even stronger defence: it strips hidden data and anything that isn’t a real image.

Generate your own names, such as ${randomUUID()}.png. Store the original name in your database if you want to show it — never use it as a path.

For documents shared with other users, consider virus scanning (for example ClamAV) before making them available.

Where to store files

Saving uploads to the app server’s disk is tempting, but it causes problems in production:

  • Containers and many hosting platforms wipe the disk on every deployment.
  • With several app instances, a file saved on one isn’t on the others.
  • Disks fill up, and backups get complicated.

Use object storage instead — Amazon S3, Cloudflare R2, Google Cloud Storage, Azure Blob Storage, or self-hosted MinIO. They store unlimited files cheaply and durably, and serve them fast. Most speak the S3 API, so one client library works with all of them:

JavaScript
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';

const s3 = new S3Client({ region: process.env.S3_REGION, endpoint: process.env.S3_ENDPOINT });

await s3.send(new PutObjectCommand({
  Bucket: process.env.S3_BUCKET,
  Key: `avatars/${user.id}/${randomUUID()}.png`,
  Body: req.file.buffer,
  ContentType: 'image/png',
}));

Save the object’s key in your database (e.g. on the user row), not the file itself.

Large files: presigned uploads

Passing a 2 GB video through your Node server ties up memory, bandwidth and a connection for minutes. Instead, let the browser upload directly to storage. Your API only hands out permission:

Two ways to handle uploads. Through your server for small files: the browser sends a multipart form, multer applies size and type limits, the bytes are checked against magic numbers, and the file goes to object storage under a random key. Direct to storage for large files: the browser asks your API, which signs a URL and returns it; the browser then PUTs the file directly to object storage such as S3 or R2.

JavaScript
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';

app.post('/uploads/presign', requireLogin, validate({ body: presignSchema }), async (req, res) => {
  const key = `videos/${req.user.id}/${randomUUID()}.mp4`;
  const url = await getSignedUrl(
    s3,
    new PutObjectCommand({ Bucket: process.env.S3_BUCKET, Key: key, ContentType: 'video/mp4' }),
    { expiresIn: 300 }, // valid for 5 minutes
  );
  res.json({ url, key });
});

The browser PUTs the file to url, then tells your API the upload finished (sending key). Your server never handles the bytes. A background job can then check the file and process it.

Serving files back

  • Public files (avatars, course images): serve from the storage bucket or a CDN in front of it.
  • Private files (invoices, submissions): keep the bucket private, check permissions in your API, then redirect to a short-lived presigned download URL (GetObjectCommand + getSignedUrl).
  • If you ever serve user files from your own domain, set Content-Disposition: attachment and the correct Content-Type so an uploaded HTML file can’t run scripts on your site.

Upload checklist: limits on size and count · content-based type checks · random storage names · object storage, not local disk · private by default · processing in a background job.

Exercise

An avatar upload endpoint

Create PUT /me/avatar that accepts one file field named avatar: at most 2 MB, JPEG/PNG/WebP only. Check the file's first bytes (not just its MIME type), save it under a random name, and return its URL. Respond 413 for too-large files and 415 for wrong types.

JavaScript
import multer from 'multer';

const upload = multer({
  // your options here
});

app.put('/me/avatar', requireLogin, upload.single('avatar'), async (req, res) => {
  // your code here
});

Summary

  • Browsers send files as multipart/form-data; express.json() can’t read it — use multer.
  • Always set limits on file size and count, and reject unexpected fields.
  • Don’t trust the file name, extension or MIME type — check the content and generate your own names.
  • Store files in object storage (S3, R2, GCS), not on the app server’s disk.
  • For large files, let the browser upload directly to storage with a presigned URL.