Handling File Downloads

1. Using Content-Disposition Header

Header ValueBehavior
inlineDisplay in browser if possible
attachmentForce download dialog
attachment; filename="report.pdf"Suggested filename (ASCII)
filename*=UTF-8''r%C3%A9sum%C3%A9.pdfRFC 5987 Unicode filename

2. Implementing Streaming Downloads

MethodNotes
Chunked Transfer-EncodingHTTP/1.1; no Content-Length needed
HTTP/2 streamsNative streaming
BackpressurePause read when client buffer full
Avoid loading full file in memoryUse file streams / S3 GetObject pipe

3. Using Range Requests

Example: Range Request

GET /videos/large.mp4 HTTP/1.1
Range: bytes=1024-2047

HTTP/1.1 206 Partial Content
Content-Range: bytes 1024-2047/52428800
Content-Length: 1024
Accept-Ranges: bytes
Content-Type: video/mp4
<1024 bytes>

4. Implementing Resume Support

HeaderPurpose
Accept-Ranges: bytesServer advertises range support
Range: bytes=N-Resume from byte N
If-Range: ETagResume only if file unchanged
206 Partial ContentSuccessful range response

5. Setting Content-Type Header

File TypeMIME
PDFapplication/pdf
JSONapplication/json
CSVtext/csv
ZIPapplication/zip
PNG / JPEG / WebPimage/png / image/jpeg / image/webp
MP4 / WebMvideo/mp4 / video/webm
Unknown binaryapplication/octet-stream

6. Generating Temporary Download URLs

TechLifetime
S3 presigned URL1s - 7d
Signed JWT in URLCustom expiration
Signed cookies (CloudFront)Cover multiple downloads from one session

7. Implementing Download Authorization

PatternTrade-off
API proxy + auth checkFull control, more bandwidth
Pre-signed URL after authOffload to CDN/storage
Token in query (short-lived)Simple; logs may leak token

8. Handling Download Errors

StatusCause
404File not found
410File expired/deleted
416 Range Not SatisfiableRange outside file
403Permission denied

9. Providing File Metadata

MethodPurpose
HEAD requestGet size, type, last-modified without body
Sibling endpointGET /files/{id} returns metadata; /files/{id}/content returns bytes
Header echoX-Filename, X-Checksum

10. Implementing ZIP Archives

ApproachNotes
Stream ZIP creationarchiver (Node), zip4j (Java)
Pre-generated ZIPCache for popular bundles
ZIP64Required for files > 4 GB or > 65k entries
Compression level0 (store) for already-compressed media