File uploads look simple in a prototype: a client selects a file, the server accepts it, and storage persists it. In production, the same flow must handle interrupted connections, partial transfers, forged content types, filename collisions, malicious documents, abandoned sessions, and expensive processing. A reliable design does not merely confirm that bytes reached the server. It establishes that the upload is complete, authorized, intact, scanned, and safe to expose.
This guide presents a practical design for resumable uploads, integrity verification, quarantine storage, controlled publication, and operational cleanup.
Define the file lifecycle first
Do not let a storage object alone represent the business state of a file. Keep a separate application record with an explicit lifecycle, such as:
- Initiated: An upload session exists but no complete data has been received.
- Uploading: Parts are being accepted and progress is recorded.
- Assembled: The parts have been combined, but security checks are incomplete.
- Quarantined: The object is isolated while scanning or content analysis runs.
- Available: The file passed the required checks and may be retrieved.
- Rejected or Expired: The file failed validation or the incomplete session timed out.
The API should return an application-level file identifier and upload-session identifier. Download authorization should depend on the lifecycle state, not simply on whether an object exists in storage.
Use multipart transfers for large files
A single request carrying a large file creates a poor failure boundary. If the connection breaks near the end, the client may have to resend the entire body. Multipart upload divides the file into parts and sends each part independently, allowing a failed part to be retried without repeating successful work.
A typical protocol looks like this:
POST /uploadscreates an upload session.- The server validates authorization, declared size, and the intended file purpose.
- The client sends parts to an endpoint such as
PUT /uploads/{id}/parts/{partNumber}. - The server validates and records each accepted part.
- The client sends a completion request containing the known parts.
- The server verifies the recorded parts, assembles the object, and advances the lifecycle.
Define the part-size and numbering rules in the API contract. The final part may be smaller than the others, but the server should explicitly decide whether gaps, duplicate part numbers, and out-of-order delivery are allowed.
Make part acceptance idempotent
Clients retry requests when a timeout occurs, even when the server has already processed the original request. If repeating a part upload creates an inconsistent state, ordinary network failures become data-integrity failures.
A practical uniqueness rule is (upload_id, part_number). Store the part size, checksum, storage key, and creation time. If the same part is submitted again with identical content, return the existing result safely. If the part number is reused with different content, return a conflict instead of silently overwriting the previous part.
At completion time, do not trust the client’s list as the source of truth. The server should inspect its own part records, calculate the expected total size, detect missing parts, and verify that the completion request refers to the same upload session.
Verify integrity at two levels
A successful HTTP response does not prove that the received content is the content the client intended to send. Use at least two integrity checks:
- Part-level verification: Calculate or validate a checksum for each part.
- Object-level verification: After assembly, validate the final size and, where supported, the checksum of the complete object.
Distinguish transport-integrity checks from security controls. A checksum can detect accidental corruption or an incomplete transfer; it does not establish that a file is authorized, benign, or appropriate for the application.
For example, Amazon S3 multipart uploads support checksums for parts and validation during completion. That mechanism helps verify data integrity, but it does not replace authorization, content inspection, or safe serving policies.
Do not trust filenames or Content-Type
A browser-provided filename is presentation metadata, not a safe storage path. It may contain path components, unusual characters, Unicode ambiguities, or a name that collides with an existing object. Generate the storage key within the application and keep the original name only as bounded metadata when the product needs to display it.
The Content-Type header is also client-controlled and can be spoofed. Use an allowlist of formats required by the product, validate the file signature or content on the server, and reject formats that do not serve a clear business purpose. Keep image, document, archive, and media parsers up to date because parsing untrusted files expands the attack surface.
Publish only after quarantine checks
Do not place a new object directly in a location where users or application processors can consume it before inspection completes. Write it first to a quarantine area. Depending on the file type and threat model, a scanning service, sandbox, or content disarm and reconstruction process can inspect the object.
A scanner error should not automatically become an approval. Use a separate state such as ScanFailed, apply bounded retries, and preserve the scan engine version, timestamp, and result for investigation. If the file is rejected, keep the rejection reason useful but avoid exposing sensitive internal details to the uploader.
Separate storage from access control
Store uploaded files outside the web root or in an object-storage system that is not directly mapped to user-controlled paths. Expose an internal file identifier rather than the physical object key. On download, the application can authorize the request and then stream the object or issue a short-lived access URL.
Be deliberate when files are rendered in a browser. Set appropriate Content-Disposition and Content-Type values, and consider whether a file could contain active content. HTML, SVG, office documents, and archive files may create different risks from ordinary images. If a format is not required, block it. If it is required, use an isolated delivery domain and apply suitable browser security policies.
Support resumable downloads where useful
Resumability is not limited to uploads. HTTP range requests allow a client to request a byte range instead of the full representation. This is useful for large downloads, media seeking, and recovering from a dropped connection. A server that returns partial content must describe the selected range correctly, and clients should only combine partial responses when they refer to the same strong representation validator.
If your application implements range support, test boundary conditions such as an empty file, an unsatisfiable range, overlapping ranges, and a file that changes during transfer. For immutable objects, a strong version identifier or validator helps prevent combining bytes from different versions.
Clean up abandoned sessions
Multipart uploads create temporary state. Record the last activity time for every session and run a periodic cleanup job for sessions that have exceeded the product’s retention window. The cleanup operation should be safe to repeat: attempting to delete an already removed part or session should not turn a successful cleanup into an incident.
Track operational signals such as:
- Started, completed, rejected, and expired uploads.
- Average and p95 upload duration.
- Part retry rate and checksum failures.
- Quarantine backlog and oldest waiting item.
- Storage consumed by abandoned sessions.
- Scan failures and processing latency.
Implementation checklist
- Associate each upload session with a user, purpose, size limit, and expiration time.
- Provide multipart transfer and safe retry semantics.
- Validate both part-level and complete-object integrity.
- Generate storage keys on the server.
- Treat filenames and media types as untrusted input.
- Keep objects quarantined until required checks finish.
- Authorize every download independently from upload authorization.
- Apply rate, size, concurrency, and storage quotas.
- Clean up incomplete sessions and observe the cleanup process.
Reliable file upload is a lifecycle and verification problem, not just an endpoint implementation. Multipart transfer limits the cost of network failures, checksums expose accidental corruption, quarantine prevents premature publication, and an explicit access layer keeps storage details out of the security boundary. Together, these controls turn a fragile upload form into an operationally manageable production capability.
0 Comments