Multipart Uploads and Content Validation
Accept UploadFile inputs, validate MIME types and size limits, and guard against malicious payloads.
Why Multipart Uploads Matter
Regular JSON request bodies cannot carry raw binary files efficiently. To upload an image, PDF, or video, browsers send a multipart/form-data request, which packs each field (text values and file bytes) into separate parts with their own headers.
FastAPI exposes incoming files through two helpers:
- UploadFile — a spooled file object that keeps small files in memory and large files on disk automatically.
- File() — a parameter marker that tells FastAPI to read this value from the multipart body.
In this lesson you will accept uploads, validate their MIME type and size, and reject malicious or oversized payloads before they touch your storage.
Your First UploadFile Endpoint
An UploadFile parameter gives you the original filename, the declared content_type, and async methods like read() and seek(). Always declare it with = File(...) so FastAPI parses it from the multipart body.
Note the handler is async because file I/O on UploadFile is awaitable.
from fastapi import FastAPI, UploadFile, File
app = FastAPI()
@app.post("/upload")
async def upload(file: UploadFile = File(...)):
contents = await file.read()
return {
"filename": file.filename,
"content_type": file.content_type,
"size_bytes": len(contents),
}All lessons in this course
- Multipart Uploads and Content Validation
- Streaming Responses and Range Requests
- Offloading Storage to S3-Compatible Buckets
- Async Image and Document Transformation