Difficulty: Intermediate
How do you handle file uploads in FastAPI? What is the difference between File and UploadFile?
`File` is a basic bytes object - the entire file is loaded into memory. `UploadFile` is a file-like object with metadata (filename, content_type) and supports async reading, making it suitable for large files.
`UploadFile` provides: - `filename`: Original filename - `content_type`: MIME type - `read(size)` / `await file.read()`: Read content - `seek(offset)` / `write()`: Seek/write operations - The file is spooled in memory up to a threshold, then stored on disk
For multiple files, use `List[UploadFile]`.
from fastapi import FastAPI, File, UploadFile
from typing import List
import shutil
import os
app = FastAPI()
@app.post("/upload")
async def upload_file(file: UploadFile = File(...)):
# Read file content
content = await file.read()
# Save to disk
file_path = f"uploads/{file.filename}"
os.makedirs("uploads", exist_ok=True)
with open(file_path, "wb") as f:
f.write(content)
return {
"filename": file.filename,
"content_type": file.content_type,
"size": len(content)
}
@app.post("/upload-multiple")
async def upload_multiple(files: List[UploadFile] = File(...)):
results = []
for file in files:
content = await file.read()
results.append({"filename": file.filename, "size": len(content)})
return results
UploadFile, File, multipart/form-data, streaming