File Uploads

How a server receives a file sent from a form or client, and what happens to it once it arrives.

What is it?

Most data a backend receives is simple text: JSON with strings and numbers. Sometimes a client needs to send a real file, like a profile picture, a PDF, or a spreadsheet. Files are binary, often large, and usually come with regular form fields (a caption, a category) in the same request. Raw JSON isn't well suited to carrying binary content alongside those fields.

Browsers and servers use a request format called multipart form data for this. It packs one or more files and regular fields into a single request, each part separated and labeled.

On the server, a small library (like multer in Node.js) unpacks the request. It saves each file somewhere (disk, memory, or straight to cloud storage) and gives your route handler its details.

Explain like I'm 10

A multipart request is like a padded envelope with several separately wrapped, labeled items: a letter (a text field), a photo (a file), and a receipt (another field). The person opening it (the server) can tell what each piece is, instead of getting one unlabeled blob.

Examples

Accepting a single file upload with multer

const multer = require("multer");
const upload = multer({ dest: "uploads/" });

app.post("/profile-picture", upload.single("avatar"), (req, res) => {
  console.log(req.file);   // { filename, path, size, mimetype, ... }
  console.log(req.body);   // any other regular form fields sent alongside it
  res.json({ url: `/uploads/${req.file.filename}` });
});

multer runs as middleware. It intercepts the multipart request, saves the file to disk, and attaches its details to req.file before your route handler runs.

Validating an upload before accepting it

const upload = multer({
  dest: "uploads/",
  limits: { fileSize: 2 * 1024 * 1024 }, // 2 MB max
  fileFilter: (req, file, cb) => {
    const allowed = ["image/png", "image/jpeg"];
    cb(null, allowed.includes(file.mimetype));
  },
});

Limiting file size and type at the upload layer keeps huge or unexpected files away from your app logic and storage.

How it works

When a form with a file is submitted, the browser encodes the body as multipart/form-data instead of JSON. The body is split into sections, each with a small header saying whether it's a regular field or a file. File parts also carry their original name and content type.

On the server, an upload library reads that body and extracts each file's bytes. It writes them somewhere (a temp folder, then often on to permanent or cloud storage) and fills req.file (or req.files) with metadata. Regular fields land in req.body as usual.

Why does it exist?

JSON bodies are text and aren't built to carry large binary data efficiently alongside other fields. Multipart form data is the standard way to bundle files and fields in one request. Libraries like multer save every project from writing multipart parsing by hand.

When to use it

Use multipart uploads whenever a user needs to send an actual file (images, documents, videos) rather than structured text.

When not to use it

If the client only references a file hosted elsewhere (a URL), or sends a small amount of binary data, plain JSON with a base64-encoded string can be simpler. It's less efficient for large files, though.

Common mistakes

  • Not limiting file size or type, so huge or unexpected files can exhaust disk space or memory.

  • Storing uploads inside the app's codebase directory instead of separate, dedicated storage.

  • Trusting the client-reported file extension or MIME type as proof of what the file contains.

Practice exercises

  1. Easy:

    Set up a route that accepts a single file under the field name 'document' and returns its saved filename.

  2. Medium:

    Add a 5MB file size limit and reject larger uploads with a clear error message.

  3. Hard:

    Explain why a file's declared MIME type alone doesn't prove it's a safe image, and describe one extra check you could add.

Interview questions

What is multipart form data and why is it used for file uploads?

A request format that bundles files and regular form fields together, each part separated and labeled. Plain JSON isn't well suited to carrying large binary content alongside text fields.

What role does a library like multer play in handling uploads?

It parses the multipart request, extracts the files, saves them (to disk, memory, or on to cloud storage), and exposes their metadata to the route via req.file or req.files.

Why should you limit file size and validate file type on the server, not just the frontend?

A request can skip the frontend entirely, so limits enforced only there give no real protection against oversized or malicious uploads.

What's the difference between multer's `memoryStorage` and `diskStorage`?

memoryStorage keeps the whole file in RAM, via req.file.buffer. It's simple but risky for large files or many concurrent uploads, since it can exhaust memory. diskStorage streams the file to a temp location on disk, using less memory per upload, but you must clean up those temp files.

Why is streaming an uploaded file directly to storage preferable to fully loading it into memory first, for large files?

Streaming handles the file in small chunks as they arrive, so memory use stays roughly constant whatever the file size. Loading the whole file first makes memory grow with file size, which can exhaust the server under concurrent large uploads.

What's the security risk of trusting a file's client-reported MIME type or extension?

Both are metadata the client supplies and can be forged. A file named photo.jpg claiming image/jpeg could be a completely different format. Verify the real content on the server, e.g. by inspecting the file's byte signature.

Why store uploaded files outside the application's own served codebase directory, or in dedicated object storage like S3?

Uploads inside the codebase risk being served or executed as part of the app. They also complicate deployments that replace the whole codebase, and don't scale across multiple server instances the way shared storage does.

What happens if `upload.single(fieldName)` receives a request where the client used a different field name than expected?

req.file isn't set at all. The middleware only looks under that exact field name, so the route should check that req.file exists instead of assuming it.

Why should an uploaded file be given a new, generated filename on the server rather than keeping the client-supplied original filename?

The original name is attacker-controlled. It can contain path traversal sequences or odd characters, or clash with another user's file. A server-generated unique name, like a UUID, avoids both the security risk and accidental overwrites.

How does `upload.array(fieldName, maxCount)` differ from `upload.single(fieldName)`?

.single() expects exactly one file under that field name and fills req.file. .array() accepts several files under the same field name, up to maxCount, and fills req.files as an array.

Why might you validate an image upload's actual pixel dimensions or re-encode it server-side, beyond checking its MIME type and size?

A file can pass type and size checks and still be a crafted image that exploits a bug in an image library, or a small file with enormous decoded dimensions. Re-encoding through a trusted image library normalizes the format and neutralizes most such attacks.

What HTTP status code would you typically return if an upload exceeds the configured size limit?

413 Payload Too Large. Multer's fileSize limit raises an error that the route or error middleware should catch and turn into this response, instead of a generic crash.

Why is `multipart/form-data` less efficient than raw binary transfer, and when is that trade-off still worth it?

Multipart adds boundary markers and headers around each part, which makes the payload somewhat larger than raw bytes. It's worth it whenever a file must travel with other form fields in one request, which a raw binary body can't do.

Why check a file's extension or magic-byte signature, in addition to its declared MIME type?

A MIME type is one header value that's easy to spoof. An extension or byte-signature check adds an independent check an attacker must also get right, so one forged value isn't enough to slip a disguised file through.

Why does an upload route usually need both a `fileFilter` and a size limit?

A size limit still lets any small file type through. fileFilter runs during parsing and rejects unwanted MIME types before the file is written to storage. They guard against different problems, so you need both.

What happens to `req.body` fields sent alongside a file in the same multipart request?

They're parsed onto req.body as usual. Multer puts the file parts in req.file/req.files and leaves text fields on req.body, so the route gets both.