How-To Guide

How to Build Content-Disposition Headers for Downloads

Generate safe Content-Disposition headers for downloads, handle non-ASCII filenames with RFC 5987 encoding, and avoid header injection.

On this page

  1. Introduction
  2. Choose the disposition type
  3. Encode non-ASCII filenames
  4. Sanitize against header injection
  5. Set the header and related headers
  6. Verify across clients
  7. Common pitfalls
  8. Conclusion

Introduction

When a service produces a file such as an export, a generated report, or a user upload that is being echoed back, the client needs to know whether to display it in the browser or save it to disk, and under what name. The Content-Disposition header answers both questions. It is simple in the common case and surprisingly sharp-edged at the edges: non-ASCII filenames, spaces and quotes, and header injection all turn a one-line header into a security and compatibility problem.

This tutorial builds a small, well-tested helper that emits a correct Content-Disposition value for any filename. It covers the inline versus attachment distinction, the dual-parameter encoding that keeps old clients working, the sanitization that prevents response splitting, and the tests that confirm a browser saves the file under the intended name.

Choose the disposition type

The disposition type is either inline or attachment. Inline tells the browser to render the content in the current context if it knows how; attachment forces a save-or-open dialog with the provided filename. For user-generated or untrusted content, prefer attachment, because inline content that the browser renders can execute scripts under your origin if the type is mistaken. A file upload service that serves a stored HTML file inline creates a stored cross-site scripting path; forcing attachment removes it.

The filename parameter is optional and is only meaningful alongside a disposition type. Provide it whenever the URL path does not already convey a good name, which is common for endpoints such as /export?id=42. Include the name for attachment responses specifically, because that is the name the browser uses for the saved file.

Encode non-ASCII filenames

Historically the filename parameter held an ASCII value in quotes. That cannot represent a name with an accent, a Chinese character, or an emoji. RFC 6266 solves this with a second parameter, filename*, whose value carries an explicit charset and percent-encoding: filename*=UTF-8’’%E6%8A%A5%E5%91%8A.pdf. Modern browsers prefer filename* when present and fall back to filename for older clients. Emit both: an ASCII-safe fallback and the encoded extended value.

The fallback should be a best-effort transliteration with any remaining non-ASCII characters replaced by an underscore, so that a client ignoring filename* still saves a recognizable file. Do not simply drop the fallback, because a deprecated client that sees only filename* may ignore the whole header and use a generic name.

function contentDisposition(type, filename) {
  const clean = filename
    .replace(/[\r\n\u0000-\u001f\u007f]/g, '') // strip CR, LF, controls
    .replace(/[\\/:*?"<>|]/g, '_')               // strip path and reserved chars
    .slice(0, 255) || 'download';
  const ascii = clean.replace(/[^\x20-\x7e]/g, '_');
  const encoded = encodeURIComponent(clean).replace(/['()*]/g, (c) =>
    '%' + c.charCodeAt(0).toString(16).toUpperCase());
  return type + "; filename=\"" + ascii + "\"; filename*=UTF-8''" + encoded;
}

Sanitize against header injection

A header value is terminated by a carriage return and line feed. If a filename can contain those bytes and they reach the header, an attacker can inject additional response headers or a second status line. The classic vector is a user-supplied filename in an upload-echo endpoint. Always strip CR, LF, NUL, and other control characters before composing the header, and do the sanitation after decoding so percent-encoded control bytes cannot slip through.

Strip path separators as well. A name such as ../../etc/passwd does not by itself let the server write outside its directory, but it confuses clients, some of which normalize the name and save to an unexpected location. Replace slashes and backslashes with an underscore. Also strip the characters that break the quoted-string grammar, such as the double quote and the backslash, since they would terminate the parameter early.

Set Content-Disposition alongside a correct Content-Type and, when the size is known, a Content-Length. For attachments, a generic application/octet-stream forces the download even for types the browser could render. If you want the browser to offer a sensible default application, send the real media type; if you want to guarantee a save dialog, use the octet-stream type. When caching is not desired for per-user exports, add Cache-Control: private, no-store so a shared cache does not retain another user’s file.

For range and resume support on large exports, keep the Content-Disposition header identical on the 206 responses so a download manager retains the filename across resumed chunks.

import { createServer } from 'node:http';

function sendExport(req, res, filename, buffer) {
  res.writeHead(200, {
    'content-type': 'application/octet-stream',
    'content-length': buffer.length,
    'content-disposition': contentDisposition('attachment', filename),
    'cache-control': 'private, no-store',
    'x-content-type-options': 'nosniff',
  });
  res.end(buffer);
}

createServer((req, res) => sendExport(req, res, 'Q3 报告 (final).pdf', Buffer.from('data'))).listen(3000);

Verify across clients

Test with a filename that combines a space, an accent, a CJK character, a quote, and a control character. Inspect the raw header with curl and confirm that CR and LF never appear, that the quoted fallback exists, and that the filename* parameter is present and correctly percent-encoded. Then download through a real browser and confirm the saved name matches the human-readable expectation.

curl -sD - -o /dev/null http://localhost:3000/export | grep -i content-disposition
# expect a single header line, quoted fallback, and filename*=UTF-8''...

Common pitfalls

Dropping the ASCII fallback, sending a raw unencoded UTF-8 name, forgetting to strip CR and LF, and using inline for untrusted content are the four failures that appear most often in review. Each has a concrete fix: always emit both parameters, encode with the RFC 5987 grammar, sanitize control characters after decoding, and default untrusted downloads to attachment. A small helper with these rules baked in removes the temptation to inline the header at each call site.

Conclusion

Content-Disposition is a two-parameter header: a quoted ASCII fallback for compatibility and an RFC 5987 encoded value for the real name. Sanitize control characters and path separators before composing it, never let CR or LF reach the value, and prefer attachment for anything the user did not author. Verify with both curl and a browser, because the failure mode is a silently wrong saved filename. As a self-check, write a unit test that feeds a filename with an embedded carriage return and asserts the parsed header contains exactly one disposition and no injected second header.

Keep the header construction in one tested function so every download endpoint shares the same encoding and the same hardening.

Sources: RFC 6266: Content-Disposition in HTTP, MDN: Content-Disposition header, RFC 5987: Language and charset parameters.

FAQ

Why does my download save as download.bin?
Browsers ignore a Content-Disposition filename they cannot decode. If only a raw UTF-8 name is sent without the filename* parameter and ASCII fallback, many clients fall back to the URL path or a generic name. Send both a quoted fallback and an RFC 5987 encoded value.
Can a filename cause header injection?
Yes. A carriage return or line feed inside the value lets an attacker inject additional headers. Always strip CR, LF, and control characters before writing the header, or reject the filename outright.

Related Examples