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)
raisePoints:
UploadFileis 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.sizeis 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_sizein nginx), a pure ASGI middleware that counts bytes of the stream, and recent Starlette limits such asmax_part_sizeandmax_files. Content-Lengthcheck: cheap first line of defence, but clients can lie or use chunked encoding.- Do not use
file.filenamein paths (traversal) or trustcontent_type. Sniff magic bytes or use a library, restrict extensions, and generate server-side names. - Blocking disk writes inside
async defstall the loop for large chunks; use a thread (anyio.to_thread.run_sync) oraiofilesfor heavy loads, or declare the endpointdef. - 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: attachmentand 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