← Back to Tutorials

18. File Upload

pip install python-multipart
from fastapi import FastAPI, UploadFile, File
from fastapi.responses import JSONResponse

app = FastAPI()

# Single file upload
@app.post("/upload/")
async def upload_file(file: UploadFile = File(...)):
    contents = await file.read()
    return {
        "filename": file.filename,
        "content_type": file.content_type,
        "size": len(contents)
    }

# Save file to disk
import aiofiles

@app.post("/save/")
async def save_file(file: UploadFile = File(...)):
    async with aiofiles.open(f"uploads/{file.filename}", "wb") as f:
        await f.write(await file.read())
    return {"message": "File saved", "filename": file.filename}

# Multiple files
from typing import List

@app.post("/upload-multiple/")
async def upload_multiple(files: List[UploadFile] = File(...)):
    return {"filenames": [f.filename for f in files]}

# File validation
@app.post("/validated-upload/")
async def validated_upload(file: UploadFile = File(...)):
    if file.content_type not in ["image/jpeg", "image/png", "application/pdf"]:
        return JSONResponse(
            {"error": "Only JPEG, PNG, PDF allowed"},
            status_code=400
        )
    return {"filename": file.filename}
✏️ Exercise: Create an endpoint that accepts a single image file, validates it's a JPEG/PNG, saves it to disk, and returns the file size and dimensions.