Learning objectives
After reading this article you will be able to:
- Understand where FastAPI and Flask keep the file before your function runs
- Validate type, signature and size and send the file to storage with boto3
- Generate a presigned URL so the browser uploads directly, then check the result
On this page
- Where does the file sit before your function runs?
- What do you need before you start?
- How do you validate and send the file with boto3?
- How do you receive the upload in FastAPI?
- How do you receive the upload in Flask?
- How do you let the browser upload straight to storage?
- How do you test it, and which errors show up?
- How to do this on Square Cloud
- FAQs
A form with <input type="file"> reaches FastAPI and Flask in a few lines of code. The hard part comes after: storing the file somewhere that survives the next deploy, stopping someone from sending 30 GB and filling the disk, and refusing a script renamed to .png.
This guide takes the file from the form to any S3-compatible storage, with one upload module serving both frameworks. At the end, it shows the alternative where the browser uploads straight to storage. If you are still choosing a framework, see FastAPI, Flask or Django.
Where does the file sit before your function runs?#
In both frameworks, the multipart/form-data body is read and written down before your code sees the file:
| FastAPI | Flask | |
|---|---|---|
| Object you receive | UploadFile |
FileStorage in request.files |
| Where the file sits | SpooledTemporaryFile: memory up to 1 MB (Starlette's default), then disk |
Memory if small, otherwise a temporary file |
| File object for boto3 | file.file |
file.stream |
| Type declared by the client | file.content_type |
file.mimetype |
| Built-in size limit | None | MAX_CONTENT_LENGTH |
That has two consequences. Memory stays under control, because large files go to the system's temporary directory. On the other hand, by the time your function checks the size, the whole file is already on disk. So the limit has to come before the read: in Flask, with MAX_CONTENT_LENGTH; in FastAPI, with the middleware in its section below.
It's also why the final destination can't be a folder on the server. In many environments it vanishes on every deploy, as files that disappear after a deploy explains.
What do you need before you start?#
Python with a virtual environment, a bucket on an S3-compatible storage service and a key pair with write access. Install the framework you'll use:
pip install "fastapi[standard]" boto3 # FastAPI (includes python-multipart and uvicorn)
pip install flask boto3 python-dotenv # Flask (python-dotenv loads .env on flask run)Credentials go in a .env file, outside the repository:
S3_ENDPOINT=https://s3.example.com
S3_REGION=us-east-1
S3_BUCKET=my-bucket
S3_ACCESS_KEY=your-access-key
S3_SECRET_KEY=your-secret-keyHow do you validate and send the file with boto3?#
The module below knows nothing about either framework: it takes a binary file object and the declared type, validates them and uploads. Save it as storage.py:
# storage.py
import os
import uuid
import boto3
from boto3.s3.transfer import TransferConfig
from botocore.config import Config
from botocore.exceptions import ClientError
s3 = boto3.client(
"s3",
endpoint_url=os.environ.get("S3_ENDPOINT"), # omit on AWS S3
region_name=os.environ["S3_REGION"],
aws_access_key_id=os.environ["S3_ACCESS_KEY"],
aws_secret_access_key=os.environ["S3_SECRET_KEY"],
config=Config(
signature_version="s3v4",
# S3_PATH_STYLE=true swaps the bucket.host address for host/bucket
s3={"addressing_style": "path" if os.environ.get("S3_PATH_STYLE") == "true" else "auto"},
),
)
BUCKET = os.environ["S3_BUCKET"]
LIMIT = 20 * 1024 * 1024 # 20 MB per file
# accepted type -> stored extension and the format's first bytes
TYPES = {
"image/jpeg": ("jpg", b"\xff\xd8\xff"),
"image/png": ("png", b"\x89PNG\r\n\x1a\n"),
"application/pdf": ("pdf", b"%PDF-"),
}
TRANSFER = TransferConfig(
multipart_threshold=16 * 1024 * 1024, # multipart above 16 MB (default: 8 MB)
multipart_chunksize=16 * 1024 * 1024,
max_concurrency=4, # threads per upload (default: 10)
)
class InvalidFile(Exception):
def __init__(self, status: int, message: str):
super().__init__(message)
self.status, self.message = status, message
def send(file, content_type: str | None) -> str:
kind = TYPES.get(content_type)
if kind is None:
raise InvalidFile(415, "file type not allowed")
ext, signature = kind
file.seek(0, os.SEEK_END)
if file.tell() > LIMIT:
raise InvalidFile(413, "file is larger than the limit")
file.seek(0)
if file.read(len(signature)) != signature:
raise InvalidFile(415, "content does not match the type")
file.seek(0)
key = f"uploads/{uuid.uuid4()}.{ext}"
s3.upload_fileobj(
file, BUCKET, key, ExtraArgs={"ContentType": content_type}, Config=TRANSFER
)
return key # store the key in your database, next to the file's ownerValidation has three layers, because OWASP reminds you that an upload's Content-Type comes from the user and is trivial to spoof. First, the declared type has to be on the list. Then the first bytes have to match the format (FF D8 FF for JPEG, 89 50 4E 47 0D 0A 1A 0A for PNG and %PDF- for PDF, according to the WHATWG MIME Sniffing standard). Finally, the size is measured on the file itself, with seek and tell, without trusting any header.
The key is a UUID plus the extension you picked. The original filename never becomes a path, not even after Werkzeug's secure_filename: keep it in your database if you want to show it.
upload_fileobj reads the file object in chunks and, above multipart_threshold, splits the upload into parts sent from several threads. boto3's documentation requires the file to be in binary mode, which is how both frameworks hand it over. ContentType in ExtraArgs makes the storage answer with the right type when someone downloads the file. To resume interrupted uploads of very large files, see multipart and resumable uploads.
How do you receive the upload in FastAPI?#
# main.py
from fastapi import FastAPI, Request, UploadFile
from fastapi.responses import JSONResponse
from storage import LIMIT, InvalidFile, send
app = FastAPI()
@app.exception_handler(InvalidFile)
async def invalid_file(request: Request, e: InvalidFile):
return JSONResponse({"detail": e.message}, status_code=e.status)
@app.middleware("http")
async def cap_body(request: Request, call_next):
# FastAPI writes the whole file before calling the route: refuse it first
if request.url.path == "/upload":
length = request.headers.get("content-length", "")
if not length.isdigit():
return JSONResponse({"detail": "send a Content-Length"}, status_code=411)
if int(length) > LIMIT + 64 * 1024: # room for the other fields
return JSONResponse({"detail": "file is larger than the limit"}, status_code=413)
return await call_next(request)
@app.post("/upload", status_code=201)
def upload(file: UploadFile): # def, not async def: boto3 blocks the thread
return {"key": send(file.file, file.content_type)}The parameter name (file) is the form field name. The route is a plain def on purpose: FastAPI's documentation says to use def with libraries that don't support await, and boto3 is one of them. FastAPI runs the route in a thread pool, and the process keeps serving other requests during the upload. Inside a def, file.file is the real SpooledTemporaryFile, which boto3 accepts as is.
The middleware reads only the Content-Length header, which browsers and curl send for forms, and refuses the body before it's written. The tell() check inside send still applies to the file itself. If a proxy sits in front, a body limit configured there is one more guard against a full disk.
How do you receive the upload in Flask?#
# app_flask.py
from flask import Flask, abort, request
from storage import LIMIT, InvalidFile, send
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = LIMIT + 64 * 1024 # whole body: file and fields
@app.errorhandler(InvalidFile)
def invalid_file(e: InvalidFile):
return {"detail": e.message}, e.status
@app.post("/upload")
def upload():
file = request.files.get("file")
if file is None or file.filename == "":
abort(400, "no file sent")
return {"key": send(file.stream, file.mimetype)}, 201With MAX_CONTENT_LENGTH, Flask raises RequestEntityTooLarge (413) as soon as the request passes the limit. mimetype is the declared type, lowercased and without parameters, and stream is the file object where Werkzeug kept the bytes. To put it online with Gunicorn or Uvicorn, follow how to host FastAPI, Flask or Django.
How do you let the browser upload straight to storage?#
For large files, the best option is for the file to skip your process entirely. The API generates a presigned URL for a PUT, the browser uploads straight to storage and then tells the API. Add to storage.py:
def upload_url(content_type: str) -> dict:
kind = TYPES.get(content_type)
if kind is None:
raise InvalidFile(415, "file type not allowed")
key = f"uploads/{uuid.uuid4()}.{kind[0]}"
url = s3.generate_presigned_url(
"put_object",
Params={"Bucket": BUCKET, "Key": key, "ContentType": content_type},
ExpiresIn=300, # 5 minutes; the browser sends the same Content-Type
)
return {"url": url, "key": key}
def confirm(key: str) -> int:
try:
size = s3.head_object(Bucket=BUCKET, Key=key)["ContentLength"]
except ClientError as e:
if e.response["Error"]["Code"] == "404":
raise InvalidFile(404, "file not found")
raise
if size > LIMIT:
s3.delete_object(Bucket=BUCKET, Key=key)
raise InvalidFile(413, "file is larger than the limit")
return sizeThen add the routes to FastAPI's main.py (in Flask, read the same fields from request.get_json()):
from pydantic import BaseModel
from storage import confirm, upload_url
class UrlRequest(BaseModel):
content_type: str
class Uploaded(BaseModel):
key: str
@app.post("/upload-url")
def new_upload_url(body: UrlRequest):
return upload_url(body.content_type)
@app.post("/upload-url/confirm")
def confirm_upload(body: Uploaded): # also check that the key belongs to the caller
return {"key": body.key, "size": confirm(body.key)}A PUT URL accepts whatever file arrives, of any size up to the storage limit, so the check moves to after the upload: head_object measures the object and anything over the limit is deleted. To check the signature, a get_object with Range="bytes=0-15" fetches only the start of the file. The browser side and the bucket's CORS are in CORS errors on direct uploads.
How do you test it, and which errors show up?#
Start one of the two servers and send a file with curl:
uvicorn main:app --env-file .env --port 8000 # FastAPI
flask --app app_flask run --port 8000 # Flask (reads .env on its own)
curl -i -F "file=@photo.jpg;type=image/jpeg" http://localhost:8000/upload
curl -i -F "file=@notes.txt;type=image/png" http://localhost:8000/uploadThe first should return 201 with {"key":"uploads/....jpg"}; the second, 415. Check the object with aws s3api head-object --bucket my-bucket --key <key> --endpoint-url "$S3_ENDPOINT": ContentLength and ContentType must match the file you sent.
The most common errors:
RuntimeError: Form data requires "python-multipart" to be installed.FastAPI needs python-multipart to read forms. It ships with fastapi[standard]; with plain fastapi, install it separately.
422 with "type":"missing" and "loc":["body","file"]. The form field name isn't the route parameter's name, or the form was sent without enctype="multipart/form-data".
Empty request.files in Flask. Same causes: the <form> lacks the enctype or the field has another name. In a fetch with FormData, don't set Content-Type by hand: the browser has to include the boundary.
The server stops responding during uploads. The FastAPI route was declared with async def and calls boto3, which blocks the event loop. Switch to def.
AccessDenied or SignatureDoesNotMatch. A key without permission, the wrong region or a clock that's off; see AccessDenied and SignatureDoesNotMatch on S3. If the storage rejects uploads after a boto3 update, set AWS_REQUEST_CHECKSUM_CALCULATION=WHEN_REQUIRED, as explained in the best S3 client tool.
No space left on device. The temporary directory filled up with uploads in progress. Lower the body limit or move large files to direct browser uploads.
How to do this on Square Cloud#
On Square Cloud's Blob Storage, storage.py runs after changing only the .env: S3_ENDPOINT=https://s3-blob.squarecloud.app, S3_REGION=auto, S3_PATH_STYLE=true and the S3 keys you derive from an API key in the "S3 access" tab of the dashboard. S3_BUCKET is public or private, the two fixed buckets you write to: images anyone may see go in public, delivered by a global edge CDN, and users' documents go in private, which only opens through a temporary link or a share link.
Each file can be up to 10 GB, and above 100 MB the upload has to be multipart. The example's TransferConfig already goes multipart from 16 MB, so the route through the server stays the same. A single PUT through a presigned URL, on the other hand, works for files up to 100 MB; above that, combine the presigned URL with multipart. SigV4 presigned URLs last up to 7 days, although minutes are enough for an upload, and CORS already accepts PUT from any origin; the API key needs write permission and the plan has to be active.
Blob's folder rules set a maximum size and the allowed extensions for everything uploaded to the folder, one more barrier for what arrives through a presigned URL. There is no ingress fee for uploads or egress fee for downloads, and every plan includes a storage quota. Explore Blob Storage.
Blob Storage
S3-compatible object storage with no egress fees
FAQs
UploadFile or bytes in FastAPI?
UploadFile. With bytes, FastAPI reads the whole file into memory. UploadFile uses a temporary file that stays in memory up to a limit and then moves to disk, and it exposes the file object boto3 accepts.
How do I limit the upload size in Flask?
Set app.config['MAX_CONTENT_LENGTH'] in bytes. A larger request makes Flask raise RequestEntityTooLarge, which becomes a 413 response. On the development server, the client may see a connection reset instead of the 413.
Can I use async def with boto3 in FastAPI?
You can, but boto3 blocks the thread while it uploads, and inside an async def that stalls every request in the process. Declare the route with def: FastAPI runs it in a thread pool, as its documentation recommends.
What is the difference between upload_file and upload_fileobj in boto3?
upload_file takes the path of a file on disk. upload_fileobj takes a file object opened in binary mode, like the one FastAPI and Flask hand you. Both switch to multipart uploads in threads when the file passes the configured threshold.
More in Storage
See all 24 articles- What is a presigned (signed) URL?A presigned URL is a temporary link to a private file that works without login or credentials. See how it works, its limits and when to use it.
- What is object storage?Object storage keeps files as objects with a key and metadata, accessed over an HTTP API. See how it works, what it is for and where its limits are.
- What does 'S3-compatible' storage mean?S3 is Amazon's object storage and its API became the industry standard. Learn what S3-compatible means, what differs between providers, and how to connect.
- Uploading large files: multipart and resumable uploadsMultipart upload splits a large file into parts that are sent in parallel and retried on their own. See the Python walkthrough, how to resume, and common mistakes.