Python File Upload with FastAPI

Handle file uploads in FastAPI using UploadFile with async streaming, file size validation, MIME type checking, background task processing, and multiple.

Python Fastapi File Upload

Code

snippet
from fastapi import FastAPI, UploadFile, File, BackgroundTasks
import aiofiles
import os

app = FastAPI()
MAX_SIZE = 10 * 1024 * 1024

@app.post('/upload')
async def upload(file: UploadFile = File(...), bg: BackgroundTasks = BackgroundTasks()):
    if file.content_type not in ['image/png', 'image/jpeg', 'application/pdf']:
        return {'error': 'Unsupported type'}
    content = await file.read()
    if len(content) > MAX_SIZE:
        return {'error': 'File too large'}
    async with aiofiles.open(f'uploads/{file.filename}', 'wb') as f:
        await f.write(content)
    return {'filename': file.filename, 'size': len(content)}