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

pythonsnippet
35 lines
# 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}

How the snippet works

FastAPI Streaming Multipart Upload keeps everything in the function upload_document.

The one repetition in this snippet is the loop while chunk := await file.read(CHUNK). The asynchronous flow is linearized with await, keeping exception handling local. From fastapi it pulls Path, FastAPI, File, HTTPException, UploadFile — the imports name exactly which library surface the snippet touches. HTTPException is the guard’s signal — thrown at the branch, before any partial work happens.

It builds and returns a fresh value rather than reusing its inputs.

Caveats

  • Plan for an install step: fastapi and aiofiles are a real dependency, resolved by the package manager.
  • The guard file.content_type not in ALLOWED short-circuits the flow with an early raise when its condition holds.

Applying it

The main signature reads def upload_document(file: UploadFile = File(...)

Callers only need upload_document — everything else stays internal.

Statements that matter

return {'filename': final.name, 'bytes': written, 'type': file.content_type}
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)

FAQ

Does `upload_document` modify its input?
It does not. Inputs are only read; the return value is freshly built.
What happens if the preconditions do not hold?
Validation comes first — `HTTPException` marks the failure at `file.content_type not in ALLOWED`, before any partial work happens.
What does this need from the package registry?
These are real dependencies: `fastapi` and `aiofiles`. Without them the snippet will not load.