A reliable file download endpoint depends on more than returning a stream. This guide explains which HTTP headers to send for attachments, inline previews, resumable downloads, and cached files, then turns those rules into a practical implementation checklist you can use during endpoint reviews and troubleshooting.
Overview
The right response headers tell the browser what the file is, whether it should be displayed or saved, how large it is, and whether a client may request only part of it. They also give caches and download managers enough information to validate or resume transfers.
A typical download response may include these headers:
Content-Type: application/pdf
Content-Disposition: attachment; filename="report.pdf"
Content-Length: 248731
Accept-Ranges: bytes
Cache-Control: private, max-age=3600
ETag: "file-version-42"
X-Content-Type-Options: nosniff
Not every response needs every header. The correct set depends on whether the resource is public or private, static or generated, intended for download or preview, and capable of serving byte ranges.
Header reference
| Header | Purpose | Typical guidance |
|---|---|---|
Content-Type | Describes the media type. | Send the actual type, such as application/pdf or image/jpeg. |
Content-Disposition | Controls inline display or download behavior and suggests a name. | Use attachment for downloads and inline for supported previews. |
Content-Length | Reports the response size in bytes. | Send it when known and stable; do not guess for dynamically compressed or streamed content. |
Accept-Ranges | Signals support for partial requests. | Use bytes only when the endpoint correctly handles ranges. |
Content-Range | Describes the returned portion of a ranged response. | Send with a 206 Partial Content response. |
Cache-Control | Sets caching behavior. | Choose policy based on confidentiality, versioning, and regeneration cost. |
ETag | Identifies a representation version. | Use it for conditional requests and cache validation. |
Checklist by scenario
1. Attachment download
For a normal save-to-disk response, start with a precise media type and an attachment disposition:
HTTP/1.1 200 OK
Content-Type: application/zip
Content-Disposition: attachment; filename="project-export.zip"
Content-Length: 1048576
X-Content-Type-Options: nosniff
Quote the ASCII fallback filename, and account for filenames containing spaces or punctuation. For international filenames, use the extended filename* parameter with UTF-8 encoding while retaining a safe fallback:
Content-Disposition: attachment; filename="document.pdf"; filename*=UTF-8''r%C3%A9sum%C3%A9.pdf
Generate the filename on the server rather than copying an untrusted path or header value directly. Strip path separators and control characters, and consider a server-side identifier when the original name is not trustworthy.
2. Inline preview
Use inline only when displaying the file in the browser is an intentional part of the product:
Content-Type: application/pdf
Content-Disposition: inline; filename="invoice.pdf"
X-Content-Type-Options: nosniff
Preview behavior varies by browser and media type. A file that is safe to download is not automatically safe to render in a page. Treat HTML, SVG, XML, and other active or script-capable formats with particular care. If users need to preview untrusted content, consider converting it to a safer representation or serving it from an isolated origin with an appropriate content security policy.
3. Large or resumable downloads
Range support is useful for large files, interrupted transfers, media seeking, and download managers. A client may send:
Range: bytes=1000000-1999999
If the range is valid, the server should return 206 Partial Content, include the selected byte interval and total size, and send only that portion:
HTTP/1.1 206 Partial Content
Accept-Ranges: bytes
Content-Range: bytes 1000000-1999999/52428800
Content-Length: 1000000
Content-Type: application/octet-stream
For an unsatisfiable range, return 416 Range Not Satisfiable and, when the total size is known, provide a value such as Content-Range: bytes */52428800. Do not advertise Accept-Ranges: bytes unless the storage layer, application server, and proxy path preserve correct range behavior.
4. Private or user-specific files
Headers do not replace authorization. Authenticate the request, authorize access to the specific object, and avoid exposing predictable storage paths. For sensitive responses, a conservative starting point is:
Cache-Control: private, no-store
Content-Disposition: attachment; filename="private-report.pdf"
X-Content-Type-Options: nosniff
Use no-store when retaining a copy in browser or intermediary storage would be inappropriate. For less sensitive user-specific files, a controlled private cache policy may be acceptable, but document that decision and test it with the browsers and proxies used by your application.
5. Public, versioned files
Public assets with immutable URLs can use a longer freshness period if your deployment process changes the URL when the bytes change. An ETag or Last-Modified validator can still help clients check whether their cached representation is current. Avoid treating a long cache lifetime as a substitute for versioned naming: changing bytes at the same URL can leave users with stale content.
What to double-check
- Content type: Determine the type from trusted file metadata and a controlled allowlist where possible. Do not rely only on a user-supplied extension.
- Length accounting: Confirm that
Content-Lengthmatches the bytes actually sent. Compression, encryption, and on-the-fly transformation can change the final length. - Conditional requests: Test
If-None-Matchwith yourETag. An unchanged representation can return304 Not Modifiedwithout a response body. - Range and validators: Check that partial responses do not combine bytes from different file versions. A stable validator helps clients identify the representation they are resuming.
- HEAD requests: If your API supports
HEAD, make its metadata consistent withGET, while returning no body. - Proxies and object storage: Verify which headers your framework, CDN, reverse proxy, or object-storage service preserves or overrides. A correct application response can change in transit.
- Cross-origin access: If a browser application must read a response header, configure the relevant CORS exposure deliberately. A header being present on the network does not mean frontend JavaScript can read it.
- Failure responses: Ensure authorization failures and missing files return the intended status and do not accidentally inherit a successful file's content type, cache policy, or body.
Use browser developer tools and command-line requests to inspect real responses. Test a normal GET, a HEAD, a conditional request, a valid range, an invalid range, and an unauthorized request. Also test filenames containing spaces, Unicode characters, quotes, and unexpected path-like input.
Common mistakes
- Sending
Content-Disposition: attachmentfor every file. This prevents intentional previews and makes the browser experience less useful. Choose inline or attachment per resource and product requirement. - Trusting the filename extension. Extensions can be misleading or deliberately changed. Validate uploads before processing and use a safe type policy for serving them. See the file validation and sanitization guide for the broader workflow.
- Advertising range support without implementing it. Clients may retry with ranges and receive corrupt or incomplete files. Remove the signal or fix range handling.
- Using a wildcard cache policy for private data. Shared caches and browser history have different implications. Make confidentiality and cache scope explicit.
- Building headers by string concatenation. Unsanitized names can introduce malformed headers or response-splitting risks. Use framework APIs that correctly encode header values and reject control characters.
- Assuming a successful upload guarantees a successful download. Storage permissions, object keys, proxy limits, expiration, and response metadata can fail independently. Compare the upload and download paths when troubleshooting transfer issues.
For signed or temporary URLs, keep authorization, expiration, and response-header overrides within the signing model. A useful implementation checklist is covered in the guide to secure presigned file URLs.
When to revisit
Review download headers whenever you change storage, CDN or proxy configuration, framework response helpers, compression, authorization, or filename handling. Revisit them before a seasonal traffic increase or a migration to object storage, because those changes can expose assumptions about caching, range requests, and response metadata.
Also schedule a check when users report files that will not resume, open in the wrong application, download under the wrong name, or appear stale. Capture the complete response and request headers rather than relying on the browser's displayed behavior.
Final implementation checklist
- Set the correct
Content-Typefrom trusted metadata. - Choose
inlineorattachmentintentionally. - Sanitize and safely encode the suggested filename.
- Send
Content-Lengthonly when it describes the actual response. - Implement and test
Accept-Ranges,206,Content-Range, and416together. - Set cache directives according to whether the file is public, private, mutable, or immutable.
- Use an
ETagor another validator when conditional retrieval is useful. - Add
X-Content-Type-Options: nosniffand isolate risky previews. - Test the response through every proxy, CDN, and object-storage layer.
Keep this checklist beside the endpoint tests. When a workflow or infrastructure component changes, rerun the same cases so the download contract remains observable, secure, and predictable.