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

okcleanreferenceUploadpre-signed URL or APIValidatesize, magic bytes, allow-listProcessre-encode, scanStoreobject storage, random keyServeseparate domain, nosniff
A safe upload pipeline.

Attacks and defences

AttackExampleDefence
Web shell executionshell.php uploaded to /uploadsStore outside web root / object storage; no execution
Stored XSS via SVG/HTMLSVG with <script>Serve from separate domain, attachment, sanitise or rasterise SVG
Content-type spoofingevil.exe renamed to photo.jpgMagic-byte detection, allow-list
Denial of serviceHuge files, zip bombsSize limits, decompression limits
Path traversalfilename="../../app.js"Never use client filenames for paths
Malware distributionInfected PDF shared with othersAV scanning, quarantine

Direct uploads

BrowserAPIObject storageScanner workerrequest upload URL (type, size)pre-signed PUT (expires 5 min, size-limited)PUT fileobject created eventclean → mark available
Direct-to-storage uploads with post-upload scanning.

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 data

Serve 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: sandbox

Common 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.

More Security articles