← Back to FastAPI, page 4

fastapi-0078 · Medium mid

How do you handle large file uploads in FastAPI safely: chunked reading, size limits, temporary files and early rejection?

UploadFile wraps a SpooledTemporaryFile, so large uploads spill to disk instead of memory, but reading the whole file with await file.read() loads it into RAM. Read in fixed-size chunks, count bytes, and abort with 413 when a limit is exceeded, deleting the partial file. Reject early by checking Content-Length (which can be wrong or missing) and enforce limits at the proxy as well. Validate type by content, never trust filename or content type, and store with generated names.

Full answer

Why care: unlimited uploads allow memory exhaustion, disk filling and slow-client attacks.

Pattern:

python
@app.post("/upload")
async def upload(file: UploadFile):
    size = 0
    target = UPLOAD_DIR / f"{uuid4().hex}.bin"
    try:
        with open(target, "wb") as out:
            while chunk := await file.read(1024 * 1024):
                size += len(chunk)
                if size > MAX_BYTES:
                    raise HTTPException(413, "File too large")
                out.write(chunk)
    except HTTPException:
        target.unlink(missing_ok=True)
        raise

Points:

  • UploadFile is a spooled temp file: kept in memory up to a threshold (1 MB by default in Starlette), then on disk. await file.read(n) reads asynchronously in a thread. file.size is available once the form is parsed.
  • Multipart parsing happens before your function runs, so the whole body has already been received (and spooled) by the time you count bytes. For true early rejection use the proxy limit (client_max_body_size in nginx), a pure ASGI middleware that counts bytes of the stream, and recent Starlette limits such as max_part_size and max_files.
  • Content-Length check: cheap first line of defence, but clients can lie or use chunked encoding.
  • Do not use file.filename in paths (traversal) or trust content_type. Sniff magic bytes or use a library, restrict extensions, and generate server-side names.
  • Blocking disk writes inside async def stall the loop for large chunks; use a thread (anyio.to_thread.run_sync) or aiofiles for heavy loads, or declare the endpoint def.
  • For very large files, use direct-to-object-storage uploads with pre-signed URLs, so the API never touches the bytes. Resumable protocols (tus, S3 multipart) handle flaky networks.
  • Scan for malware if files are shared with other users, and serve downloads with Content-Disposition: attachment and the correct type.
python
import tempfile
from pathlib import Path
from uuid import uuid4

from fastapi import FastAPI, HTTPException, UploadFile
from fastapi.testclient import TestClient

UPLOAD_DIR = Path(tempfile.mkdtemp())
MAX_BYTES = 2 * 1024 * 1024
CHUNK = 256 * 1024
app = FastAPI()


@app.post("/upload")
async def upload(file: UploadFile):
    size = 0
    target = UPLOAD_DIR / f"{uuid4().hex}.bin"             # never use file.filename in a path
    try:
        with open(target, "wb") as out:
            while chunk := await file.read(CHUNK):
                size += len(chunk)
                if size > MAX_BYTES:
                    raise HTTPException(status_code=413, detail=f"Limit is {MAX_BYTES} bytes")
                out.write(chunk)
    except HTTPException:
        target.unlink(missing_ok=True)                     # remove the partial file
        raise
    return {"stored_bytes": size, "original_name_ignored": file.filename}


c = TestClient(app)
small = c.post("/upload", files={"file": ("../../etc/passwd", b"x" * 500_000, "text/plain")})
print(small.status_code, small.json())
big = c.post("/upload", files={"file": ("big.bin", b"y" * (3 * 1024 * 1024), "application/octet-stream")})
print(big.status_code, big.json())
print("files left on disk:", len(list(UPLOAD_DIR.iterdir())))

Standalone script. Run it with `python file.py`; it calls the app through TestClient, so no server is needed. Output (ran twice with identical results; Python 3.13.5, FastAPI 0.165.1, Pydantic 2.14.4, Starlette 1.10.0, SQLAlchemy 2.1.9, httpx 0.29.0): 200 {'stored_bytes': 500000, 'original_name_ignored': '../../etc/passwd'} 413 {'detail': 'Limit is 2097152 bytes'} files left on disk: 1

Key points

  • UploadFile spools to disk, but read() without a size loads everything
  • Count bytes in chunks and return 413 over the limit; delete partial files
  • Enforce limits at the proxy; Content-Length can lie
  • Never trust filename or content type; generate names
  • Large files: pre-signed uploads straight to object storage

Common mistakes

  • Calling await file.read() with no size on large files
  • Using file.filename to build a path
  • Trusting content_type for validation
  • Leaving partial files behind after an aborted upload
  • Relying only on Content-Length

Follow-ups

  • How do pre-signed uploads work?
  • How would you count bytes in a pure ASGI middleware before parsing?
  • How do you verify the real file type?

Tips

  • Show the chunk loop
  • State where limits belong
  • Mention generated filenames