Use UploadFile (a spooled file that does not load everything in memory) with the python-multipart package installed; read in chunks for large files, validate the content type and size, and never trust the client's filename.
from fastapi import File, HTTPException, UploadFile
MAX_BYTES = 5 * 1024 * 1024
@app.post("/upload")
async def upload(file: UploadFile = File(...)):
if file.content_type not in {"application/pdf", "text/plain"}:
raise HTTPException(status_code=415, detail="Unsupported file type")
size = 0
while chunk := await file.read(1024 * 1024): # stream in 1 MB chunks
size += len(chunk)
if size > MAX_BYTES:
raise HTTPException(status_code=413, detail="File too large")
# write chunk to disk or object storage here
return {"filename": file.filename, "size": size}