Sub topic 2
The simple path: multipart uploads through your API server
This chapter covers the simplest way to accept a file: the browser sends it to your API server, and your server handles it. It assumes you know HTTP methods, headers, and status codes. It also assumes you have a client, an API server, and a database, and that you can read one server-side language and browser JavaScript.
Most teams should start here. You need to know where this approach breaks down so you can move off it at the right time.
What a multipart/form-data request looks like
Browsers send files with the multipart/form-data content type. The body is a series of parts separated by a boundary string. Each part has its own headers, and a file part also carries a filename and a content type.
POST /api/avatar HTTP/1.1
Host: api.example.com
Content-Type: multipart/form-data; boundary=----form7MA4YWxk
Content-Length: 20481
------form7MA4YWxk
Content-Disposition: form-data; name="caption"
Me at the beach
------form7MA4YWxk
Content-Disposition: form-data; name="file"; filename="beach.jpg"
Content-Type: image/jpeg
<binary bytes>
------form7MA4YWxk--Three details matter for security and correctness:
- The
filenameand the part'sContent-Typeare claims made by the client. They can be wrong or hostile. - The boundary is chosen by the sender, so your parser must find it from the
Content-Typeheader and never hard-code it. - A text field and a file can share one request, so a single upload can carry metadata such as a caption.
A minimal server
The browser side is a plain FormData post. Do not set the Content-Type header yourself. The browser must add the boundary, and a manual header would leave it out.
async function uploadAvatar(file, caption) {
const form = new FormData();
form.append("caption", caption);
form.append("file", file);
const res = await fetch("/api/avatar", { method: "POST", body: form });
if (!res.ok) {
throw new Error(`Upload failed with status ${res.status}`);
}
return res.json();
}The server below uses Flask. It limits the request size, generates its own file name, and streams the file to disk instead of trusting the client's name.
import os
import uuid
from flask import Flask, jsonify, request
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 5 * 1024 * 1024 # 5 MiB, enforced by Flask
UPLOAD_DIR = "/var/uploads"
ALLOWED_TYPES = {"image/jpeg": ".jpg", "image/png": ".png"}
@app.post("/api/avatar")
def upload_avatar():
file = request.files.get("file")
if file is None:
return jsonify(error="missing file field"), 400
extension = ALLOWED_TYPES.get(file.mimetype)
if extension is None:
return jsonify(error="unsupported type"), 415
# Never use file.filename for the path. Generate your own name.
stored_name = f"{uuid.uuid4().hex}{extension}"
file.save(os.path.join(UPLOAD_DIR, stored_name))
# In a real service, insert a row in your database here.
return jsonify(id=stored_name), 201This code is short, and that is its appeal. There is one endpoint, one deployment, and the usual authentication and database transaction apply. If the upload fails, you return an error and nothing is half-finished.
Where the file goes during the request
The framework has to hold the incoming bytes somewhere while it parses the body. Most frameworks use a mix of strategies:
| Strategy | How it works | Cost |
|---|---|---|
| Buffer in memory | The whole file sits in RAM until the handler finishes | Memory use grows with file size times concurrent uploads |
| Spool to a temporary file | Small parts stay in memory, larger ones spill to disk | Needs temporary disk space and cleanup |
| Stream to the destination | The parser hands chunks to your code as they arrive | Needs a streaming parser and more careful code |
Many frameworks default to the first or second strategy. Check what yours does before you raise a size limit. A 2 GiB limit with 50 concurrent users could mean 100 GiB of buffered data.
Limits you must set at every layer
An upload is a long request. A client on a slow connection can hold a worker for minutes. Set limits in each layer that the request passes through:
- Reverse proxy or load balancer. nginx rejects bodies over 1 MB by default with
413 Payload Too Large, which is a common surprise. Raiseclient_max_body_sizedeliberately. - Application framework. Set a maximum body size, as
MAX_CONTENT_LENGTHdoes above. - Timeouts. Request, read, and idle timeouts must allow slow clients without allowing an endless trickle of bytes.
- Gateway limits. Managed gateways often cap payloads. Amazon API Gateway, for example, limits request payloads to 10 MB, and AWS Lambda limits synchronous invocation payloads to 6 MB.
The Content-Length header lets you reject an oversized upload early, but a client can lie, and chunked transfer encoding has no declared length. Always enforce the limit while reading the body, not only from the header.
Failure modes
The simple path has problems that show up as traffic grows.
- Worker starvation. With a thread-per-request or process-per-request server, each slow upload occupies a worker for its whole duration. A few dozen mobile users on weak networks can leave no workers for normal API calls.
- Double bandwidth. The bytes cross your network twice: once from the client to your server, then again from your server to storage. You pay for both and add a hop that can fail.
- No recovery. If the connection drops at 95%, the client starts again from zero. Nothing in a single
POSTsupports resuming. - Local disk is not shared. Saving to
/var/uploadsworks on one machine. With several instances behind a load balancer, a file saved on one instance is missing on the others. Local disk is also lost when a container is replaced. - Coupled scaling. Upload traffic is bandwidth heavy and CPU light. API traffic is the opposite. Running both in one process means you scale them together.
- Request-time work. Image resizing or virus scanning inside the handler makes the user wait and ties up the worker even longer.
The diagram below compares the data path with the direct approach you will meet in later chapters.
Making the simple path safer
If you choose this path, apply these habits from the start:
- Generate the stored name yourself, as in the example. A client-supplied filename such as
../../etc/cron.d/jobcan cause path traversal if you join it to a directory. - Allow only the types you need, using an allowlist, and check them against the file's content as well as its declared type. A later chapter covers content signatures.
- Store files outside the web root so an uploaded script is never executed or served directly.
- Keep file metadata (owner, original name, size, type) in the database and the bytes elsewhere.
- Return the right status codes:
400for a malformed request,413for too large,415for an unsupported type, and201for success.
When this approach is the right choice
Proxying is a reasonable decision, not just a beginner's shortcut, when these conditions hold:
- Files are small, such as avatars, documents under a few megabytes, or form attachments.
- Upload volume is low or moderate.
- You need to inspect or transform the bytes before accepting them, and you want one place to do it.
- You want one simple flow for authentication, authorization, and database writes.
Consider moving to direct-to-storage uploads when any of these appear: files over tens of megabytes, mobile users on poor networks, workers saturated by uploads, or a need for resumable transfers. The next chapters cover object storage and how to make that change.
Summary of trade-offs
| Concern | Proxied upload | Direct to storage |
|---|---|---|
| Implementation effort | Low | Higher |
| Server bandwidth | Carries every byte | Carries none |
| Large files | Poor | Good |
| Resumable | Not without extra work | Supported by multipart upload |
| Central control of bytes | Full | Needs a post-upload check |
Exercise
Your API runs behind nginx, and the Flask app has MAXCONTENTLENGTH set to 20 MiB. Users report that 3 MB uploads fail with a 413 error, but 500 KB uploads work. Where is the most likely cause, and what should you change?
Show answer
The reverse proxy is the likely cause, not the application. nginx defaults client_max_body_size to 1 MB and rejects larger bodies with 413 before they reach Flask. Raise client_max_body_size to match the application limit (for example 20m), and keep the application limit as a second check.
Exercise
A handler saves uploads using os.path.join(UPLOAD_DIR, file.filename). Name two problems with this and how to fix them.
Show answer
First, the filename is client-controlled, so a value such as ../../app/config.py can write outside the upload directory (path traversal) or overwrite existing files. Second, two users uploading photo.jpg collide. Fix both by generating the stored name on the server, for example with a UUID plus an extension chosen from an allowlist, and keep the original name only as database metadata.