In this guide
Your project lets users upload a profile photo, a report PDF or an assignment file. It works in the demo, then the first real user uploads a 200 MB video, another uploads a file with a misleading name, and a third uploads a script that your server happily stores and later serves. None of this is a rare edge case — it is what happens when an upload feature is built without validation, storage decisions and size limits.
This guide adds file uploads to a web app properly: the form, server-side validation, a storage choice, size limits, and the mistakes that turn a simple feature into a security problem.
Quick answer
Build file uploads in four layers. First, an HTML form with enctype="multipart/form-data" and a file input. Second, server-side validation of the file type and size — never trust the browser's checks alone. Third, store the file outside the web root (or in object storage) under a generated name, never the name the user supplied. Fourth, enforce a size limit at the server and the reverse proxy, and return a clear error when a file is too big or the wrong type. The most common student mistake is validating only in JavaScript: anyone can bypass that in seconds, so the server must repeat every check.
| Layer | What it does | Where it runs |
|---|---|---|
| Form | Collects the file from the user | Browser |
| Validation | Checks type, size and content | Server (always) |
| Storage | Saves the file safely | Server disk or object storage |
| Limits | Caps size and count per request | Server and reverse proxy |
| Feedback | Tells the user what went wrong | Browser, from the server's response |
How file uploads actually work
A file upload is an HTTP POST request with the body encoded as multipart/form-data. The browser splits the request into parts: one part per form field, and one part per file, each with its own headers (file name, content type) and raw bytes. The server reads those parts, and that is where most of the work happens.
Two facts shape every decision in this guide:
- The browser lies. The file name, the content type and the file extension all come from the user's machine. A file named
photo.jpgcan contain anything, and the browser'sacceptattribute is only a hint — it filters the file picker, it enforces nothing. - The server pays for every byte. An upload consumes memory, disk and bandwidth before your code even looks at it. Without limits, one large upload can fill a small server's disk or exhaust its memory.
The form
The HTML side is short. The two details that matter are the encoding type and the input attributes:
<form action="/upload" method="post" enctype="multipart/form-data">
<label for="report">Upload your report (PDF, max 10 MB)</label>
<input type="file" id="report" name="report" accept=".pdf" required>
<button type="submit">Upload</button>
</form>
The accept attribute helps honest users pick the right file, and the label text tells them the rules before they try. Both are user-experience details, not security — the real checks happen on the server.
Server-side validation
Validate in this order: size first, then type, then content. Checking size first is cheap and stops oversized files before you spend time on them.
- Size. Reject anything over your limit with a 413 response and a plain message ("File too large — maximum 10 MB"). Set the limit in your framework and in your web server, so a request that bypasses the framework still stops at the proxy.
- Extension. Check the extension against an allowlist (
.pdf,.jpg,.png), not a blocklist. Blocklists fail because there is always one dangerous extension you forgot. - Content type. Read the file's magic bytes — the first few bytes that identify its real format — instead of trusting the content-type header. A PDF starts with
%PDF; a JPEG starts withFF D8 FF. Libraries exist for this in every language; use one. - Content. If you accept images, re-encode or thumbnail them with an image library. This strips embedded scripts and metadata, and confirms the file is really an image. If you accept PDFs, consider a parser that confirms the file opens cleanly.
A small Flask example shows the pattern — size and extension checks before the file is ever saved:
from flask import Flask, request
app = Flask(__name__)
app.config["MAX_CONTENT_LENGTH"] = 10 * 1024 * 1024 # 10 MB
ALLOWED = {".pdf", ".jpg", ".jpeg", ".png"}
@app.route("/upload", methods=["POST"])
def upload():
f = request.files.get("report")
if f is None or f.filename == "":
return "No file selected", 400
ext = "." + f.filename.rsplit(".", 1)[-1].lower()
if ext not in ALLOWED:
return "Only PDF, JPG and PNG files are accepted", 400
# Save under a generated name, never the uploaded name.
f.save("/srv/uploads/" + new_id() + ext)
return "Upload complete", 200
Test it from the terminal with curl, which shows exactly what the browser sends:
curl -F "report=@report.pdf" http://localhost:5000/upload
Choosing where files live
Where you store uploads depends on how many files you expect and whether more than one server is involved.
| Storage | Best for | Watch out for |
|---|---|---|
| Local disk | One server, small projects, prototypes | Disk fills up; files vanish if the server is rebuilt |
| Object storage (S3-style) | Anything with real users, multiple servers | Needs credentials and a bucket policy; costs scale with use |
| Database | Tiny files tied to a record, such as avatars | Bloats backups and slows queries once files grow |
For a college project, local disk is fine — with two rules. Store uploads outside the web root so a file can never be fetched by guessing its URL, and serve downloads through your app, which checks who is allowed to see the file before sending it. When you outgrow one server, move to object storage and serve files through signed, time-limited links instead of public URLs.
Naming and organising files
Never store a file under the name the user gave it. User-supplied names cause three problems: two users can upload the same name and overwrite each other, names can contain path characters (../) that escape your upload folder, and names can be long or encoded in ways your filesystem dislikes.
Generate the stored name yourself: a random identifier plus the validated extension, for example 9f2c41a7.pdf. Keep the original name in your database if you want to show it back to the user, and use it only as display text. Organise by date or by user id (one folder per month, or per user) so no single folder holds tens of thousands of files, which slows directory listings on some systems.
Size limits, the full stack
A limit set in only one place is a limit that fails. Set it in three places:
- The framework. Your app's maximum request size (Flask's
MAX_CONTENT_LENGTH, Express's body-parser limit, Django'sDATA_UPLOAD_MAX_MEMORY_SIZE). This is where you return a friendly error. - The web server. Nginx's
client_max_body_sizeor Apache'sLimitRequestBody, so an oversized request is rejected before it reaches your app. - The client, as a courtesy. A small JavaScript check on
file.sizebefore submit, so users get an instant message instead of waiting for a large upload to fail.
Pick the limit from the real use: 2–5 MB for photos, 10 MB for reports, more only if the feature genuinely needs it. A generous limit is not kindness — it is disk space and bandwidth you pay for.
Security: the attacks that target uploads
Uploads are one of the most attacked features on the web, and the attacks are all variations on one idea: getting the server to store or run something it should not.
- Executable uploads. A file with a
.phpor.jspextension stored inside the web root can be executed by the server if someone requests it. The fix is the allowlist plus storing outside the web root — both, not one. - Path traversal. A file name containing
../can escape the upload folder. The fix is generating the stored name yourself, as above. - Content sniffing. A browser can be tricked into treating an uploaded file as HTML or JavaScript. Serve uploads with a
Content-Disposition: attachmentheader and aContent-Typeyou set from your own validation, not from the upload. - Zip bombs and oversized images. Compressed files that expand enormously, or images with huge pixel dimensions, exhaust memory when processed. Set limits on decompressed size and image dimensions, not just the uploaded byte count.
- Denial of service. Unlimited uploads from one user fill the disk. Rate-limit uploads per user and clean up files that are never linked to a record.
Common mistakes
- Validating only in JavaScript. The browser's checks are a convenience for honest users. The server must repeat every check, because anyone can send a request with curl and skip the browser entirely.
- Trusting the file extension. An extension is a label the user controls. Check the file's magic bytes to confirm what it really is.
- Storing the uploaded file name. Overwrites, path traversal and encoding problems all come from trusting user-supplied names. Generate your own.
- Serving uploads from the web root. A stored file that can be fetched by URL is a stored file an attacker can reach. Serve through your app, with a permission check.
- No size limit anywhere. One large upload fills the disk, and a filled disk takes down the whole app, not just uploads.
- Silent failures. An upload that fails with a generic 500 error teaches the user nothing. Return the specific reason: too large, wrong type, or no file selected.
- Forgetting cleanup. Abandoned uploads accumulate forever. Delete files that are not linked to a record after a day, and delete the file when its record is deleted.
Frequently asked questions
How big should the size limit be?
As small as the feature allows. Photos: 2–5 MB. Documents: 10 MB. Only raise it when a real use case needs more, and remember the limit protects your disk and bandwidth, not just the user.
Should I store files in the database or on disk?
On disk (or object storage) for almost everything. Databases are for data, and files bloat backups and slow queries. Store only the file's path and metadata in the database.
Can I check the file type in the browser?
You can, and you should, for a fast user experience — but it is not security. The server must check again, because the browser's check can be bypassed trivially.
How do I handle multiple files in one form?
Accept a list of files, validate each one separately, and cap the total count and the total size per request. One bad file should reject only itself, not the whole batch — unless your feature needs all-or-nothing.
What about upload progress bars?
Use the browser's upload progress events on the request object. Show progress for files over a few megabytes; for small files a spinner is enough. A progress bar that jumps from 0 to 100 with no middle state is worse than none.
Do I need virus scanning?
For a college project, no — strict type validation and storing outside the web root are enough. For anything that serves files to other users, scanning is worth adding, and object-storage services often offer it as a built-in option.
Limitations
This guide covers the standard single-server upload flow. It does not cover resumable uploads for very large files (which need chunked uploads and a client library), direct-to-storage browser uploads with signed URLs (which move validation into a different place), or content-delivery networks for serving files at scale. Those are the next steps once your upload feature has real users and the simple flow is working reliably.
Need help adding uploads to your project?
If you are building a web app with file uploads — reports, photos, assignments or documents — and want validation, storage and limits set up correctly, message Projectech on WhatsApp with your stack, what users will upload, and your deadline, and you will get a quotation stating the scope, price and delivery timeline. Chat on WhatsApp