FastAPI · Lesson 8 of 15
Uploads, Streaming and Static Files
Accept files, stream large downloads and mount a static directory.
- Intermediate
- 15 min read
- 3 objectives
Before this lessonLesson 7: OAuth2 and JWT Authentication
What you will learn
- Read an UploadFile
- Stream a response
- Mount StaticFiles
Your Progress
0 of 15 lessons 0%
- Lessons0 / 15
- Completed0
- Est. time left~ 4 hours
Create a free account to keep your progress on every device.
Files are streams, not JSON. FastAPI gives you UploadFile for incoming files, StreamingResponse for outgoing, and StaticFiles for a directory of assets.
Uploads
from fastapi import File, UploadFile, HTTPException
from pathlib import Path
UPLOADS = Path("/tmp/uploads")
UPLOADS.mkdir(exist_ok=True)
ALLOWED = {"image/jpeg", "image/png", "application/pdf"}
@app.post("/files")
async def save_file(file: UploadFile = File(...)):
if file.content_type not in ALLOWED:
raise HTTPException(415, "Unsupported type")
dest = UPLOADS / file.filename
data = await file.read()
if len(data) > 5_000_000:
raise HTTPException(413, "Too large")
dest.write_bytes(data)
return {"name": file.filename, "size": len(data)}Streaming a download
from fastapi.responses import StreamingResponse
@app.get("/files/{name}")
def download(name: str):
path = UPLOADS / name
if not path.exists():
raise HTTPException(404)
return StreamingResponse(path.open("rb"), media_type="application/octet-stream",
headers={"Content-Disposition": f'attachment; filename="{name}"'})Static files
from fastapi.staticfiles import StaticFiles
app.mount("/static", StaticFiles(directory="static"), name="static")