How to Handle File Uploads in FastAPI
Introduction
FastAPI provides built-in support for file uploads with UploadFile. Combined with aiofiles for async I/O, you can handle uploads without blocking the event loop.
Step 1: Install aiofiles
pip install aiofiles
Step 2: Create Upload Endpoint
from fastapi import FastAPI, UploadFile, File
app = FastAPI()
@app.post("/upload")
async def upload(file: UploadFile = File(...)):
content = await file.read()
return {"filename": file.filename, "size": len(content)}
Step 3: Validate and Save
import aiofiles
MAX_SIZE = 10 * 1024 * 1024
ALLOWED_TYPES = ["image/png", "image/jpeg", "application/pdf"]
@app.post("/upload")
async def upload(file: UploadFile = File(...)):
if file.content_type not in ALLOWED_TYPES:
return {"error": "Unsupported type"}
content = await file.read()
if len(content) > MAX_SIZE:
return {"error": "File too large"}
async with aiofiles.open(f"uploads/{file.filename}", "wb") as f:
await f.write(content)
return {"filename": file.filename, "size": len(content)}
Conclusion
FastAPI’s async file handling is efficient and simple. The UploadFile class provides streaming access, and aiofiles ensures disk writes don’t block the event loop.