The short version
- Check every upload's size and type on the server, and check the file's first bytes as well as its extension and MIME type, because the MIME type comes from the client and is easy to fake.
- Store uploads in private object storage like S3 instead of on the server that runs your app, and scan each file for malware in a background worker before anyone can download it.
- Rename every upload to a random ID and re-encode images to strip metadata such as the GPS coordinates that phone photos often carry.
- Serve files through signed URLs that expire, for example after an hour, and only hand one out after checking that the user asking owns the file.
- Log and rate-limit both uploads and downloads, and repeat the size and type checks in the browser for fast feedback, since only the server-side checks keep an attacker out.
To secure file uploads in an API, check each file's size and type on the server, store accepted files in object storage like S3 instead of on your app server, scan them for malware in the background and rename them with their metadata stripped. Then serve them only through expiring signed URLs to users who are allowed to see them, and log and rate-limit both uploads and downloads.
Below are the seven controls I use, which line up with the OWASP File Upload Cheat Sheet, and then a Flask API that does all of them, with S3-compatible storage and ClamAV running free in Docker on your own machine. The video above covers the same seven controls.
Why uploads are a security hole
Almost every app has file uploads, and an upload endpoint is the one place where you let a stranger put arbitrary bytes on your infrastructure. Get it wrong and someone uploads a script that your server runs, or reads other users' files by guessing their paths. Plenty of people now build apps with AI without knowing how security works, and an upload route that saves request.files["file"] to a folder under its original name works fine in a demo while breaking most of the rules below.
1. Validate the file before you accept it
Start with the size. If the upload is a profile picture, there's no reason to allow 100 or 200 MB. Limit it to somewhere between 5 and 20 MB, depending on how high a resolution you want.
Then check the type against an allowlist for that one feature. A profile picture accepts PNG and JPEG and nothing else. A document picker might accept .pdf and .docx. Neither should ever accept .exe, because who knows what that runs.
Make sure the extension and the MIME type agree, then check the file's actual bytes too. The MIME type comes from the client, and OWASP calls it "trivial to spoof": rename a PHP script to avatar.png and curl sends it as image/png. Every PNG starts with the same eight bytes and every JPEG with the same three, so the server can check that the contents match. OWASP says not to rely on that check alone either, which is what the later steps are for.
2. Store files in object storage, not on your app server
Upload files to an object storage service like AWS S3 or Google Cloud Storage. Never store them on the VPS or EC2 instance that runs your application. That's asking for trouble: a file in the wrong folder can end up executed or served as part of your site, and a flood of uploads fills the disk your app needs. OWASP ranks "a different host" as the safest place for uploads. Keep the bucket private, so the only way to read a file is a link your app signs.
3. Scan for malware in the background
Once the file is in storage, scan it with an antivirus like ClamAV, in a background worker so the user doesn't wait. They get a response as soon as the upload finishes, and the server checks the file while they carry on.
In the demo, new files land in a quarantine/ folder in the bucket, and only files that pass the scan get copied to files/, where downloads come from. If you can, sandbox the processing too, so that even a malicious file that does run can't hurt your server. Here ClamAV runs in its own container, apart from the app.
4. Rename every file and strip its metadata
Give every uploaded file your own name. The demo uses a random UUID, which OWASP calls "essential". The user's filename never touches your storage, so a name with ../ in it or a second extension like .jpg.php can't do anything.
Then strip the metadata you don't need, which is most of it. A photo straight off a phone carries EXIF data, often including the GPS coordinates of where it was taken. The demo decodes the image and saves it again, which keeps only the pixels. My test photo had a camera model and GPS coordinates, and the stored copy has neither.
5. Serve files through signed URLs, after an access check
The bad way to serve files is direct paths: example.com/uploads/folder/file.txt, where anyone who knows or guesses a path gets the file. The good way goes through your app. The user asks for /files/<uuid>, your app checks they're allowed to see that file, and only then gives them a signed URL.
A signed URL is a link to a private object with a signature in its query string, which your storage provider checks. You can make it expire. I use 3,600 seconds, one hour, so even if a vulnerability leaks some links, the access doesn't last.
Check permissions on every request. If the user doesn't own the file, block the request and log it. The demo answers with a 404 instead of a 403, so an attacker can't even tell whether a file ID exists.
6. Log, monitor and rate-limit
Log every upload, every rejected upload, every download link and every denied request, with the user and the file ID. That's how you spot someone trying to get at files they shouldn't, and how you debug it when something breaks.
Rate limiting is the one that saves you money. Say you host a 5 GB video that anyone can download. Without a limit, someone downloads it again and again, and every download is 5 GB of bandwidth on your bill, until one day there's a huge invoice from AWS or Vercel. Rate-limit both the upload endpoint and the endpoint that hands out links. A signed URL works as many times as anyone likes until it expires, so for big files keep the expiry short too.
7. Validate on the client and on the server
Do all the checks on both sides. Client-side checks are for speed: if a user picks a 50 MB file or a .exe, the browser stops the upload without sending a request, so the user gets an instant answer and your server does less work.
Server-side checks are for security. Anyone can edit your frontend or skip it and send requests with curl, so the server has to reject a virus renamed to .exe on its own.
The seven controls in the demo
| Control | What it stops | Where it is in the demo |
|---|---|---|
| Validate size and type | Huge files, scripts disguised as images | upload() in app.py |
| Object storage | Uploaded files running on your app server | RustFS, an S3-compatible server |
| Background malware scan | Known malware becoming downloadable | process() and scanner.py |
| Rename and strip metadata | Path tricks, leaked GPS data | uuid4() and sanitize() |
| Signed URLs with access checks | Users reading each other's files | download_link() |
| Logging and rate limits | Abuse you never see, surprise bills | log calls and Flask-Limiter |
| Client and server checks | Slow feedback, bypassed checks | static/index.html and upload() |
Build a secure upload API in Flask
The demo accepts profile pictures (PNG or JPEG, up to 5 MB). Storage is RustFS, an open-source server that speaks the S3 API, so the same boto3 calls work against AWS S3 once you change the endpoint and keys. You need Docker and Python 3.11 or newer (I tested on 3.14).
upload-demo/ ├── docker-compose.yml ├── requirements.txt ├── scanner.py ├── app.py └── static/ └── index.html docker-compose.yml
services: storage: image: rustfs/rustfs:1.0.5 ports: - "9000:9000" environment: RUSTFS_ACCESS_KEY: devaccesskey RUSTFS_SECRET_KEY: devsecretkey clamav: image: clamav/clamav:1.5 ports: - "3310:3310" The ClamAV image ships with its virus signatures and updates them on its own. Use real secrets for the storage keys anywhere outside your laptop.
requirements.txt
flask==3.1.3 flask-limiter==4.1.1 boto3==1.44.2 pillow==13.0.0 scanner.py
import socket import struct def scan(data: bytes, host="localhost", port=3310) -> str | None: """Stream the bytes to clamd. Returns the malware name, or None if the file is clean.""" with socket.create_connection((host, port), timeout=120) as sock: sock.sendall(b"zINSTREAM\0") for start in range(0, len(data), 65536): chunk = data[start:start + 65536] sock.sendall(struct.pack(">I", len(chunk)) + chunk) sock.sendall(struct.pack(">I", 0)) reply = b"" while not reply.endswith(b"\0"): part = sock.recv(4096) if not part: break reply += part reply = reply.rstrip(b"\0").decode() if reply == "stream: OK": return None if reply.endswith(" FOUND"): return reply.removeprefix("stream: ").removesuffix(" FOUND") raise RuntimeError(f"clamd error: {reply}") This sends the file to ClamAV's daemon with its INSTREAM command, in chunks with the length in front of each, and returns the name of whatever ClamAV found.
app.py
The first part is setup. TOKENS and FILES stand in for your real auth and your database.
import io import logging import queue import threading import uuid import boto3 from botocore.config import Config from botocore.exceptions import ClientError from flask import Flask, jsonify, request from flask_limiter import Limiter from PIL import Image, ImageOps from scanner import scan logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") log = logging.getLogger("uploads") MAX_BYTES = 5 * 1024 * 1024 ALLOWED = {"png": "image/png", "jpg": "image/jpeg", "jpeg": "image/jpeg"} SIGNATURES = {"image/png": b"\x89PNG\r\n\x1a\n", "image/jpeg": b"\xff\xd8\xff"} BUCKET = "uploads" LINK_SECONDS = 3600 # Stand-in for your real auth: maps a bearer token to a user. TOKENS = {"alice-token": "alice", "bob-token": "bob"} # Stand-in for your database: file ID -> owner, type and status. FILES = {} s3 = boto3.client( "s3", endpoint_url="http://localhost:9000", aws_access_key_id="devaccesskey", aws_secret_access_key="devsecretkey", region_name="us-east-1", config=Config(signature_version="s3v4"), ) try: s3.create_bucket(Bucket=BUCKET) except ClientError as e: if e.response["Error"]["Code"] != "BucketAlreadyOwnedByYou": raise app = Flask(__name__) app.config["MAX_CONTENT_LENGTH"] = MAX_BYTES + 64 * 1024 # the file plus form overhead def current_user(): token = request.headers.get("Authorization", "").removeprefix("Bearer ") return TOKENS.get(token) limiter = Limiter( key_func=lambda: current_user() or request.remote_addr, app=app, storage_uri="memory://", # use Redis when you run more than one process ) @app.errorhandler(429) def rate_limited(e): log.warning("rate limit hit user=%s path=%s", current_user(), request.path) return jsonify(error="Too many requests, slow down"), 429 @app.errorhandler(413) def too_large(e): log.warning("upload too large user=%s", current_user()) return jsonify(error="File is over 5 MB"), 413 MAX_CONTENT_LENGTH makes Flask refuse an oversized body with a 413 before reading it. The rate limiter counts per user, or per IP address when there's no token.
The upload route does the checks from control 1, in order:
@app.post("/files") @limiter.limit("10 per minute") def upload(): user = current_user() if not user: return jsonify(error="Log in first"), 401 file = request.files.get("file") if not file or not file.filename: return jsonify(error="No file sent"), 400 ext = file.filename.rsplit(".", 1)[-1].lower() mime = ALLOWED.get(ext) if not mime or file.mimetype != mime: log.warning("rejected type user=%s name=%r mime=%s", user, file.filename, file.mimetype) return jsonify(error="Only PNG and JPEG images are allowed"), 400 data = file.read() if len(data) > MAX_BYTES: return too_large(None) if not data.startswith(SIGNATURES[mime]): log.warning("rejected content user=%s name=%r", user, file.filename) return jsonify(error="The file's contents don't match its type"), 400 file_id = str(uuid.uuid4()) s3.put_object(Bucket=BUCKET, Key=f"quarantine/{file_id}", Body=data) FILES[file_id] = {"owner": user, "mime": mime, "status": "scanning"} jobs.put(file_id) log.info("upload accepted user=%s id=%s bytes=%d", user, file_id, len(data)) return jsonify(id=file_id, status="scanning"), 202 The file goes to the bucket under a new UUID, so the original name only ever shows up in the logs. The route answers 202 Accepted straight away and leaves the scan to the worker.
The download route is control 5:
@app.get("/files/<file_id>") @limiter.limit("30 per minute") def download_link(file_id): user = current_user() if not user: return jsonify(error="Log in first"), 401 record = FILES.get(file_id) if not record or record["owner"] != user: log.warning("access denied user=%s id=%s", user, file_id) return jsonify(error="Not found"), 404 if record["status"] != "ready": return jsonify(status=record["status"]), 409 url = s3.generate_presigned_url( "get_object", Params={"Bucket": BUCKET, "Key": f"files/{file_id}"}, ExpiresIn=LINK_SECONDS, ) log.info("link issued user=%s id=%s", user, file_id) return jsonify(url=url, expires_in=LINK_SECONDS) Only the owner gets a link, and only once the file has passed the scan. The signed URL points at files/, never at quarantine/.
The last part is the background worker:
def sanitize(data: bytes) -> bytes: """Decode and re-encode the image, which drops EXIF, GPS and anything after the image data.""" image = Image.open(io.BytesIO(data)) fmt = image.format image = ImageOps.exif_transpose(image) # keep the rotation the EXIF data asked for out = io.BytesIO() image.save(out, format=fmt) return out.getvalue() def process(file_id): record = FILES[file_id] raw = s3.get_object(Bucket=BUCKET, Key=f"quarantine/{file_id}")["Body"].read() try: threat = scan(raw) if threat: record["status"] = "rejected" log.warning("malware found id=%s owner=%s threat=%s", file_id, record["owner"], threat) return clean = sanitize(raw) s3.put_object(Bucket=BUCKET, Key=f"files/{file_id}", Body=clean, ContentType=record["mime"]) record["status"] = "ready" log.info("file ready id=%s bytes=%d", file_id, len(clean)) except Exception: record["status"] = "rejected" log.exception("processing failed id=%s", file_id) finally: s3.delete_object(Bucket=BUCKET, Key=f"quarantine/{file_id}") def worker(): while True: process(jobs.get()) jobs = queue.Queue() threading.Thread(target=worker, daemon=True).start() @app.get("/") def index(): return app.send_static_file("index.html") if __name__ == "__main__": app.run(port=8000) process scans the file, re-encodes it, stores the clean copy in files/ and always deletes the quarantined original. Phones often save photos sideways with the rotation in EXIF, so without exif_transpose the stripped photos would come out rotated. The stored Content-Type comes from your allowlist.
A thread and a queue.Queue are fine for a demo. In production, use a real job queue like Celery or RQ, so scans survive a restart and can run on a separate machine.
static/index.html
<!doctype html> <html> <body> <input type="file" id="file" accept=".png,.jpg,.jpeg"> <p id="status"></p> <script> const MAX_BYTES = 5 * 1024 * 1024; const ALLOWED = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg" }; const status = document.getElementById("status"); document.getElementById("file").addEventListener("change", async (event) => { const file = event.target.files[0]; const ext = file.name.split(".").pop().toLowerCase(); if (file.size > MAX_BYTES) { status.textContent = "That file is over 5 MB."; return; } if (ALLOWED[ext] !== file.type) { status.textContent = "Only PNG and JPEG images are allowed."; return; } const body = new Source:https://dev.to/hassan_aziz_88b11714fef8b/how-to-secure-file-uploads-in-an-api-with-a-python-example-5din