The File Upload Field: What to Restrict and Why

Restricting file extensions doesn't give you security. What matters is the file's real type, its size, and where it gets stored.

The upload field looks simple, until someone sends a file you weren't expecting.

The file extension guarantees nothing

Anyone can rename virus.exe to resume.pdf. If you only check the extension, the file isn't rejected.

The right way: detect the file's real type from its first bytes (magic bytes). A real PDF starts with %PDF-; a PNG starts with a specific signature. The server has to check this, not the browser.

Limit the size in two places

Once in the browser (so the user finds out before uploading 50 MB) and once on the server (because the browser can be bypassed). The server-side limit should also live in the web server itself, not just in application code; otherwise the file is fully uploaded and then rejected, which means you've already burned the bandwidth.

Don't store the filename as-is

The filename a user sends can contain ../ or characters that mean something special to the operating system. The file should be stored under a generated name (a UUID, for example), and the original name kept only as a label in the database.

Orphaned files

A user uploads a file, then abandons the form. That file sits on disk, attached to no response. After a few months, a large share of your disk space is orphaned files.

The fix: uploaded files that haven't been attached to any response after a set period (say, 24 hours) are deleted automatically.

What to ask the user for

Use caseRecommendation
RésuméPDF only, because a Word file may open differently on your machine
Staff photoJPG/PNG, 2 MB maximum
Scanned documentsPDF or JPG, multiple files allowed

And one user-experience point: state the restriction before the user picks a file, not as an error afterwards. "PDF, 5 MB max" under the field saves the user a round trip.

Tags:file uploadsecurityform design