FastAPI File Upload with Size Limit

Handle file uploads in FastAPI with UploadFile, enforce file size limits, validate MIME types, and save to disk with unique filenames. Includes async.

PythonFastapiFile Upload

Code

snippet
from fastapi import FastAPI, UploadFile, File, HTTPException
import uuid, os

app = FastAPI()
MAX_SIZE = 10 * 1024 * 1024  # 10MB
ALLOWED_TYPES = {'image/jpeg', 'image/png', 'application/pdf'}

@app.post('/upload')
async def upload_file(file: UploadFile = File(...)):
    if file.content_type not in ALLOWED_TYPES:
        raise HTTPException(400, 'File type not allowed')
    contents = await file.read()
    if len(contents) > MAX_SIZE:
        raise HTTPException(413, 'File too large')
    filename = f'{uuid.uuid4()}.{file.filename.split(".")[-1]}'
    with open(f'uploads/{filename}', 'wb') as f:
        f.write(contents)
    return {'filename': filename, 'size': len(contents)}

What the code does

FastAPI File Upload with Size Limit keeps everything in the function upload_file.

Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed. FastAPI, UploadFile, File, HTTPException are the only symbols borrowed from fastapi — the coupling is explicit and narrow. Instead of silently continuing, the code raises HTTPException at the guard.

The return value is newly constructed — inputs are never handed back.

What to watch for

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

Using it

The primary signature is def upload_file(file: UploadFile = File(...)

Import upload_file from the file and call it — the rest of the code is implementation detail.

Key statements

return {'filename': filename, 'size': len(contents)}
with open(f'uploads/{filename}', 'wb') as f:
    f.write(contents)

Interactive Tools for This Topic

FAQ

Does `upload_file` modify its input?
No mutation happens — the function reads its input and returns a new value.
Is there a failure path for bad input?
`HTTPException` is raised at the guard (`file.content_type not in ALLOWED_TYPES`), so invalid state never reaches the main logic.
Which packages must be installed first?
Yes. The imports resolve to `fastapi`, which the package manager must provide.