20 File Upload
DodaTech
1 min read
title: File Upload in FastAPI REST APIs weight: 30 date: 2026-06-28 lastmod: 2026-06-28 description: Implement file upload in FastAPI using UploadFile and File with validation, multiple file uploads, image processing, and async file streaming for large files. tags: [api-development, fastapi]
FastAPI file upload uses UploadFile with the File class for handling single and multiple file uploads, with automatic type validation, size limits, and async streaming for memory-efficient processing.
```python
from fastapi import FastAPI, File, UploadFile, HTTPException
from typing import List
import aiofiles
import os
app = FastAPI()
UPLOAD_DIR = "uploads/"
ALLOWED_TYPES = {"image/jpeg", "image/png", "image/gif", "application/pdf"}
MAX_SIZE = 5 * 1024 * 1024 # 5MB
@app.post("/api/upload/avatar")
async def upload_avatar(file: UploadFile = File(...)):
if file.content_type not in ALLOWED_TYPES:
raise HTTPException(400, "Invalid file type")
content = await file.read()
if len(content) > MAX_SIZE:
raise HTTPException(400, "File too large")
file_path = os.path.join(UPLOAD_DIR, f"avatar_{file.filename}")
async with aiofiles.open(file_path, "wb") as f:
await f.write(content)
return {"filename": file.filename, "size": len(content)}
@app.post("/api/upload/gallery")
async def upload_gallery(files: List[UploadFile] = File(...)):
results = []
for file in files:
content = await file.read()
results.append({"filename": file.filename, "size": len(content)})
return {"files": results, "count": len(results)}
What's Next
Now learn about caching with Redis in Building REST APIs with FastAPI.
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro