How-To Guide

How to Handle File Uploads in FastAPI

Handle file uploads in FastAPI with UploadFile streaming, size limits, content checks, safe storage names, multiple files, and tests using TestClient.

On this page

  1. Introduction
  2. Install the multipart dependency and set limits
  3. Stream the upload and enforce the size limit
  4. Validate the content, not just the extension
  5. Multiple files and form fields
  6. Handle errors and cleanup
  7. Test success and failure paths
  8. Common pitfalls
  9. Conclusion

Introduction

FastAPI makes the first version of a file upload endpoint very short: declare an UploadFile parameter, await file.read(), and return a result. That version is useful for a prototype but unsafe for production. It trusts the client’s content type, reads an unbounded body into memory, writes to a user-controlled filename, and provides no cleanup path when something fails halfway through.

This tutorial builds an endpoint that streams the upload, enforces a maximum size, stores it under a generated name, validates the file signature, and returns a structured error when the request is rejected. It also covers multiple files, background work, and tests that exercise the failure paths rather than only the happy path.

Install the multipart dependency and set limits

FastAPI needs python-multipart to parse multipart/form-data:

pip install fastapi uvicorn python-multipart aiofiles filetype

aiofiles moves blocking disk writes off the event loop. filetype detects common formats from their signature bytes without invoking an external process. Neither library replaces authentication or a reverse-proxy body limit.

Set a maximum body size in one place and reuse it in validation and documentation:

from pathlib import Path

MAX_UPLOAD_BYTES = 10 * 1024 * 1024
CHUNK_SIZE = 1024 * 1024
UPLOAD_DIR = Path("uploads")
UPLOAD_DIR.mkdir(exist_ok=True)

If the service sits behind nginx, set client_max_body_size 10m; there as well. The proxy rejects obviously oversized requests before they reach Python, while the application still enforces its own limit for direct traffic and for correctness.

Stream the upload and enforce the size limit

UploadFile exposes an async read(size) method. Read fixed-size chunks, count bytes, and delete the partial file if the limit is exceeded. Do not call await file.read() without a size unless you have already proven the body is small:

import uuid
from pathlib import Path

import aiofiles
from fastapi import FastAPI, File, HTTPException, UploadFile, status

app = FastAPI()

@app.post("/upload", status_code=status.HTTP_201_CREATED)
async def upload(file: UploadFile = File(...)) -> dict[str, str | int]:
    suffix = Path(file.filename or "").suffix.lower()
    if suffix not in {".png", ".jpg", ".jpeg", ".pdf"}:
        raise HTTPException(status.HTTP_415_UNSUPPORTED_MEDIA_TYPE, "Unsupported extension")

    stored_name = f"{uuid.uuid4().hex}{suffix}"
    destination = UPLOAD_DIR / stored_name
    total = 0

    try:
        async with aiofiles.open(destination, "wb") as target:
            while chunk := await file.read(CHUNK_SIZE):
                total += len(chunk)
                if total > MAX_UPLOAD_BYTES:
                    raise HTTPException(
                        status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
                        "File exceeds the 10 MB limit",
                    )
                await target.write(chunk)
    except Exception:
        destination.unlink(missing_ok=True)
        raise
    finally:
        await file.close()

    return {"storedName": stored_name, "bytes": total}

The generated UUID removes path traversal and collisions from the stored path. The original filename is metadata, not a filesystem path. If users need to download the file later, store the original name in the database and send it through Content-Disposition with proper encoding.

HTTPException raised inside the async with block still triggers the except cleanup, so an oversized upload does not leave a partial file behind. The finally closes the upload handle even when validation fails later.

Validate the content, not just the extension

An extension and a client-supplied content_type are claims. Inspect the first bytes of the saved file and reject a mismatch:

import filetype
from fastapi import HTTPException, status

EXPECTED = {
    ".png": {"image/png"},
    ".jpg": {"image/jpeg"},
    ".jpeg": {"image/jpeg"},
    ".pdf": {"application/pdf"},
}

def verify_signature(path: Path, suffix: str) -> None:
    kind = filetype.guess(path)
    if kind is None or kind.mime not in EXPECTED[suffix]:
        path.unlink(missing_ok=True)
        raise HTTPException(
            status.HTTP_415_UNSUPPORTED_MEDIA_TYPE,
            "File content does not match its extension",
        )

Signature checks catch a renamed executable or a text file pretending to be a PDF. They do not prove the file is safe. A valid PDF can contain JavaScript, and a valid image can exploit a decoder. If uploads are served to other users, add malware scanning and serve them from a separate origin or with a restrictive Content-Security-Policy.

The filename extension check is also a policy decision. Some applications should accept any type and rely on content disposition and scanning; others need a strict allowlist. What matters is that the decision is explicit and enforced on the server.

Multiple files and form fields

FastAPI accepts a list of files and regular form fields in the same request:

from fastapi import Form

@app.post("/attachments")
async def attachments(
    files: list[UploadFile] = File(...),
    folder: str = Form(...),
) -> dict[str, int]:
    if len(files) > 5:
        raise HTTPException(status.HTTP_400_BAD_REQUEST, "At most 5 files")

    accepted = 0
    for file in files:
        # Reuse the streaming and validation helpers above.
        accepted += 1

    return {"accepted": accepted}

Apply the byte limit per file and a separate aggregate limit for the request. Ten files of 10 MB each are not a 10 MB request. Starlette’s form parser also accepts max_files and max_fields options, which bound the number of parts before your handler runs; combine those with the byte limit rather than choosing one.

For very large files, a direct-to-object-storage upload with a presigned URL avoids streaming the body through the API process. The API issues a short-lived URL scoped to a key and content length, and the client uploads directly. Validate the resulting object asynchronously before marking it available.

Handle errors and cleanup

Return specific status codes so clients can react correctly:

  • 413 for a body that exceeds the limit.
  • 415 for an unsupported type or a signature mismatch.
  • 422 for missing fields or malformed multipart requests.
  • 401 or 403 for authentication and authorization failures.
  • 507 or 503 when storage is unavailable, with a retry hint.

Do not return a 200 with {"error": ...}. A client, proxy, and monitoring system all interpret HTTP status codes; burying failure in a success response defeats them. Log the rejection reason, byte count, detected type, and request id, but never log file contents or credentials.

Cleanup must cover every failure path: signature rejection, database failure after the write, and client disconnect. A periodic job that removes orphaned uploads is a useful safety net, but it should not be the primary cleanup mechanism.

If metadata must be written to a database, use BackgroundTasks only for work that can fail without invalidating the response. A background task that writes the authoritative record after returning 201 can leave a file with no owner. Prefer a transaction-like sequence: write to a temporary key, insert metadata, then promote the object, with a reconciliation job for partial states.

Test success and failure paths

TestClient sends multipart bodies without a running server:

from fastapi.testclient import TestClient
from app import app

client = TestClient(app)

def test_upload_png():
    response = client.post(
        "/upload",
        files={"file": ("pixel.png", b"\x89PNG\r\n\x1a\n" + b"0" * 32, "image/png")},
    )
    assert response.status_code == 201
    assert response.json()["bytes"] > 0

def test_rejects_oversize(monkeypatch):
    monkeypatch.setattr("app.MAX_UPLOAD_BYTES", 8)
    response = client.post("/upload", files={"file": ("big.pdf", b"%PDF-1.7" + b"0" * 32)})
    assert response.status_code == 413

Add a wrong-signature case, a missing-file case, and an unauthenticated request if the endpoint is protected. Assert that rejected uploads do not leave files in the upload directory. Use a temporary directory in tests so runs do not pollute the workspace.

For asynchronous clients, httpx.AsyncClient with ASGITransport exercises the same application. The important property is that tests call the real handler and real streaming code, not a mocked UploadFile.

Common pitfalls

  • Reading the whole file. await file.read() without a size defeats streaming.
  • Trusting content_type. It is client input.
  • Using the original filename as a path. Traversal and collisions are both possible.
  • Returning 200 for validation errors. Clients and monitors cannot distinguish success from failure.
  • No aggregate limit. Per-file limits do not bound a multi-file request.
  • Serving user files from the app origin. A malicious HTML or SVG file can run in the application’s origin.
  • No cleanup on failure. Partial files accumulate and can fill the disk.

Conclusion

FastAPI’s UploadFile is a thin wrapper around a spooled temporary file. Production safety comes from how you use it: stream in chunks, count bytes, generate storage names, verify signatures, enforce aggregate limits, and clean up on every failure path. Tests should cover oversize and wrong-type requests, not only a successful PNG. With those pieces in place, the same endpoint can grow into a multi-file or presigned-upload design without weakening its boundaries.

Sources: FastAPI request files, Starlette forms, OWASP File Upload Cheat Sheet.

FAQ

Does FastAPI limit upload size by default?
No. FastAPI and Starlette parse the multipart body, but you must enforce an application-level byte limit while reading the file, and configure a matching limit at the reverse proxy or load balancer. A proxy limit alone is not enough because the app may be reached directly.
Is UploadFile stored in memory?
Starlette uses a spooled temporary file. Small uploads stay in memory and larger ones roll over to disk, but reading the entire file with await file.read() still materializes it in memory. Stream in chunks when the size can be large.
Can I trust file.content_type for validation?
No. content_type is supplied by the client. Use it only as an early hint, then inspect the file signature or run a parser for the expected format before accepting the upload.

Related Examples