16. File Uploads & Static Files
Many applications need to handle file uploads (images, documents, videos) and serve static files (CSS, JavaScript, images). FastAPI provides built-in support for file uploads using the UploadFile class, which is highly efficient because it streams files directly to disk without loading them into memory. To test these examples, save to main.py and run uvicorn main:app --reload.
Uploading Files
FastAPI can handle file uploads using the UploadFile type. Files are streamed, preventing memory issues with large files.
from fastapi import FastAPI, File, UploadFile from typing import List import shutil from pathlib import Path app = FastAPI() # Single file upload @app.post("/upload/") async def upload_file(file: UploadFile = File(...)): # file.filename - original filename # file.content_type - MIME type # file.file - the file-like object file_path = Path(f"uploads/{file.filename}") file_path.parent.mkdir(exist_ok=True) with file_path.open("wb") as buffer: shutil.copyfileobj(file.file, buffer) return { "filename": file.filename, "content_type": file.content_type, "size": file_path.stat().st_size } # Multiple files upload @app.post("/upload-multiple/") async def upload_multiple_files(files: List[UploadFile] = File(...)): results = [] for file in files: file_path = Path(f"uploads/{file.filename}") with file_path.open("wb") as buffer: shutil.copyfileobj(file.file, buffer) results.append({"filename": file.filename, "saved": str(file_path)}) return {"files": results}
File Validation
Always validate uploaded files to prevent security issues.
from fastapi import FastAPI, File, UploadFile, HTTPException from pathlib import Path ALLOWED_EXTENSIONS = {".jpg", ".jpeg", ".png", ".gif", ".pdf"} MAX_FILE_SIZE = 5 * 1024 * 1024 app = FastAPI() async def validate_file(file: UploadFile): ext = Path(file.filename).suffix.lower() if ext not in ALLOWED_EXTENSIONS: raise HTTPException(400, f"Extension {ext} not allowed") size = 0 chunk = await file.read(1024) while chunk: size += len(chunk) if size > MAX_FILE_SIZE: raise HTTPException(400, f"File too large. Max {MAX_FILE_SIZE} bytes") chunk = await file.read(1024) await file.seek(0) return file @app.post("/secure-upload/") async def secure_upload(file: UploadFile = File(...)): await validate_file(file) file_path = Path(f"uploads/{file.filename}") with file_path.open("wb") as buffer: shutil.copyfileobj(file.file, buffer) return {"message": "File uploaded successfully", "filename": file.filename}
Async File Upload with aiofiles
For better performance with many concurrent uploads, use aiofiles for non-blocking file I/O.
import aiofiles from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/async-upload/") async def async_upload(file: UploadFile = File(...)): file_path = f"uploads/{file.filename}" async with aiofiles.open(file_path, "wb") as buffer: while chunk := await file.read(1024 * 1024): await buffer.write(chunk) return {"filename": file.filename, "saved_to": file_path}
Serving Static Files
FastAPI can serve static files like CSS, JavaScript, and images using the StaticFiles middleware.
from fastapi import FastAPI from fastapi.staticfiles import StaticFiles from pathlib import Path app = FastAPI() app.mount("/static", StaticFiles(directory="static"), name="static") app.mount("/uploads", StaticFiles(directory="uploads"), name="uploads") # Now these URLs work: # http://localhost:8000/static/style.css # http://localhost:8000/uploads/image.jpg from fastapi.responses import HTMLResponse from fastapi.templating import Jinja2Templates from fastapi import Request templates = Jinja2Templates(directory="templates") @app.get("/", response_class=HTMLResponse) async def home(request: Request): return templates.TemplateResponse("index.html", {"request": request})
File Download Endpoints
Create endpoints that let users download files from your server.
from fastapi.responses import FileResponse from fastapi import HTTPException from pathlib import Path app = FastAPI() @app.get("/download/{filename}") async def download_file(filename: str): file_path = Path(f"uploads/{filename}") if not file_path.exists(): raise HTTPException(404, "File not found") return FileResponse( path=file_path, filename=filename, media_type="application/octet-stream" ) @app.get("/preview/{filename}") async def preview_image(filename: str): file_path = Path(f"uploads/{filename}") if not file_path.exists(): raise HTTPException(404, "File not found") return FileResponse(path=file_path)
Knowledge Check
Ready to test your understanding of 16. File Uploads & Static Files?