Secure File Uploads: Validation, Storage, Malware Scanning and Serving
Handle user file uploads safely: size and type validation, magic-byte checks, random names, storing outside the web root or in object storage, scanning.
Published December 6, 2026
File upload features are a favourite entry point for attackers: upload a PHP web shell and execute it, upload an SVG with embedded JavaScript, upload a 20 GB file to exhaust disk, or a zip bomb to crash your processor. A handful of rules make uploads safe without making them painful for users.
The concept
Validate on the server: enforce size limits early (at the proxy and application), check file type by content (magic bytes), not just by extension or the client-supplied Content-Type, and allow-list the formats you actually need. Re-encode images when possible, which strips embedded payloads and metadata such as GPS location.
Store uploads where they cannot execute: object storage (S3, GCS) or a directory outside the web root with execution disabled, under random names you generate, never the user's filename. Serve them from a separate domain or with Content-Disposition: attachment and X-Content-Type-Options: nosniff so browsers do not interpret them as HTML or scripts. Scan with antivirus for document-heavy workflows, and process archives with limits on size and file counts.
The pipeline
Attacks and defences
| Attack | Example | Defence |
|---|---|---|
| Web shell execution | shell.php uploaded to /uploads | Store outside web root / object storage; no execution |
| Stored XSS via SVG/HTML | SVG with <script> | Serve from separate domain, attachment, sanitise or rasterise SVG |
| Content-type spoofing | evil.exe renamed to photo.jpg | Magic-byte detection, allow-list |
| Denial of service | Huge files, zip bombs | Size limits, decompression limits |
| Path traversal | filename="../../app.js" | Never use client filenames for paths |
| Malware distribution | Infected PDF shared with others | AV scanning, quarantine |
Direct uploads
Practical examples
Detect real file type (Python)
Check magic bytes, not the extension.
import magic # python-magic (libmagic)
ALLOWED = {"image/png", "image/jpeg", "application/pdf"}
mime = magic.from_buffer(first_2kb, mime=True)
if mime not in ALLOWED:
raise ValueError(f"file type {mime} not allowed")Re-encode images to strip payloads and metadata
Pillow writes a clean new file.
from PIL import Image
img = Image.open(upload_stream)
img.verify(); upload_stream.seek(0); img = Image.open(upload_stream)
img.convert("RGB").save(out_path, "JPEG", quality=88) # drops EXIF, scripts, trailing dataServe user files safely
Headers that stop browsers interpreting uploads as content.
Content-Type: application/octet-stream
Content-Disposition: attachment; filename="report.pdf"
X-Content-Type-Options: nosniff
Content-Security-Policy: sandboxCommon mistakes
- Trusting file extensions or client Content-Type.
- Saving uploads inside a directory the web server executes.
- Using user-supplied filenames as storage paths.
- Serving user HTML/SVG from your main domain.
Key takeaways
- Validate size and true type; allow-list formats.
- Store with random names in non-executable storage.
- Re-encode images and scan documents.
- Serve from a separate domain with safe headers.
FAQ
Should uploads go through my server?
Direct uploads to object storage with pre-signed URLs scale better; validate and scan after upload before marking files available.
How do I limit size with pre-signed URLs?
Use pre-signed POST policies with content-length-range or provider equivalents.
Are SVGs safe?
Not by default: they can contain scripts. Sanitise them, rasterise to PNG, or serve them as attachments from an isolated domain.