FastAPI Streaming Multipart Upload

Stream large multipart uploads in FastAPI with per-part size caps, allowed content types, and chunked writes that never buffer fully.

PythonFastapiFile Upload

Code

snippet
# stream multipart parts to disk without buffering the whole file
from pathlib import Path

import aiofiles
from fastapi import FastAPI, File, HTTPException, UploadFile

MAX_BYTES = 20 * 1024 * 1024
CHUNK = 1024 * 512
ALLOWED = {'application/pdf', 'image/png'}

app = FastAPI()
STORAGE = Path('uploads')
STORAGE.mkdir(exist_ok=True)


@app.post('/documents')
async def upload_document(file: UploadFile = File(...)) -> dict:
    if file.content_type not in ALLOWED:
        raise HTTPException(415, f'unsupported type: {file.content_type}')

    written = 0
    target = STORAGE / f'{file.filename or "doc"}.part'

    async with aiofiles.open(target, 'wb') as out:
        while chunk := await file.read(CHUNK):
            written += len(chunk)
            if written > MAX_BYTES:
                await out.close()
                target.unlink(missing_ok=True)
                raise HTTPException(413, 'file exceeds size limit')
            await out.write(chunk)

    final = target.with_suffix('')
    target.rename(final)
    return {'filename': final.name, 'bytes': written, 'type': file.content_type}