CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-content-disposition

Create and parse HTTP Content-Disposition headers according to RFC 6266

Pending

Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

index.mddocs/

Content-Disposition

Content-Disposition is a Node.js library for creating and parsing HTTP Content-Disposition headers according to RFC 6266. It provides robust support for Unicode filenames, automatic fallback encoding for ISO-8859-1 compatibility, and handles the complex requirements for international characters in file downloads and attachments.

Package Information

  • Package Name: content-disposition
  • Package Type: npm
  • Language: JavaScript
  • Installation: npm install content-disposition

Core Imports

const contentDisposition = require('content-disposition');

ESM:

import contentDisposition from 'content-disposition';
// parse function available as contentDisposition.parse

Basic Usage

const contentDisposition = require('content-disposition');

// Create a basic attachment header
const header = contentDisposition('report.pdf');
// Returns: 'attachment; filename="report.pdf"'

// Set header on HTTP response
res.setHeader('Content-Disposition', contentDisposition('monthly-report.pdf'));

// Parse an existing header
const parsed = contentDisposition.parse('attachment; filename="report.pdf"');
console.log(parsed.type);        // 'attachment'
console.log(parsed.parameters);  // { filename: 'report.pdf' }

Capabilities

Header Creation

Creates a Content-Disposition header value with proper encoding and fallback support.

/**
 * Create a Content-Disposition header value
 * @param {string} [filename] - The filename to include in the header
 * @param {object} [options] - Configuration options
 * @param {string} [options.type='attachment'] - Disposition type ('attachment', 'inline', or custom)
 * @param {string|boolean} [options.fallback=true] - ISO-8859-1 fallback filename behavior
 * @returns {string} - Formatted Content-Disposition header value
 * @throws {TypeError} - If filename is not a string
 * @throws {TypeError} - If fallback is not a string or boolean
 * @throws {TypeError} - If fallback contains non-ISO-8859-1 characters
 */
function contentDisposition(filename, options);

Options:

  • type (string, default: 'attachment'): Specifies the disposition type. Can be 'attachment', 'inline', or any custom value. The type is normalized to lowercase.
  • fallback (string|boolean, default: true): Controls ISO-8859-1 fallback behavior:
    • true: Enable automatic generation of ISO-8859-1 fallback for Unicode filenames
    • false: Disable fallback, only include Unicode version
    • string: Use provided string as the ISO-8859-1 fallback filename

Usage Examples:

// Basic attachment
contentDisposition('document.pdf');
// → 'attachment; filename="document.pdf"'

// Inline disposition
contentDisposition('image.jpg', { type: 'inline' });
// → 'inline; filename="image.jpg"'

// Unicode filename with automatic fallback
contentDisposition('报告.pdf');
// → 'attachment; filename="??.pdf"; filename*=UTF-8\'\'%E6%8A%A5%E5%91%8A.pdf'

// Custom fallback
contentDisposition('€ rates.pdf', { fallback: 'EUR rates.pdf' });
// → 'attachment; filename="EUR rates.pdf"; filename*=UTF-8\'\'%E2%82%AC%20rates.pdf'

// No fallback
contentDisposition('€ rates.pdf', { fallback: false });
// → 'attachment; filename*=UTF-8\'\'%E2%82%AC%20rates.pdf'

// No filename specified
contentDisposition();
// → 'attachment'

Header Parsing

Parses a Content-Disposition header string into structured data with automatic handling of extended (Unicode) parameters.

/**
 * Parse a Content-Disposition header string
 * @param {string} string - The Content-Disposition header string to parse
 * @returns {ContentDisposition} - Parsed header object with type and parameters
 * @throws {TypeError} - If string argument is missing or not a string
 * @throws {TypeError} - If header format is invalid
 * @throws {TypeError} - If parameter format is invalid
 * @throws {TypeError} - If duplicate parameters are found
 * @throws {TypeError} - If extended field value is invalid
 * @throws {TypeError} - If unsupported charset in extended field
 */
contentDisposition.parse(string);

Usage Examples:

// Parse basic header
const result = contentDisposition.parse('attachment; filename="document.pdf"');
console.log(result.type);        // 'attachment'
console.log(result.parameters);  // { filename: 'document.pdf' }

// Parse Unicode header with extended parameter
const unicode = contentDisposition.parse(
  'attachment; filename="report.pdf"; filename*=UTF-8\'\'%E6%8A%A5%E5%91%8A.pdf'
);
console.log(unicode.type);        // 'attachment'
console.log(unicode.parameters);  // { filename: '报告.pdf' }
// Note: Extended parameter takes precedence over regular parameter

// Parse inline disposition
const inline = contentDisposition.parse('inline; filename="image.jpg"');
console.log(inline.type);        // 'inline'
console.log(inline.parameters);  // { filename: 'image.jpg' }

// Parse with no parameters
const basic = contentDisposition.parse('attachment');
console.log(basic.type);        // 'attachment'
console.log(basic.parameters);  // {}

Types

/**
 * Class representing a parsed Content-Disposition header
 * @constructor
 * @param {string} type - The disposition type (e.g., 'attachment', 'inline')
 * @param {object} parameters - Object containing disposition parameters
 */
function ContentDisposition(type, parameters) {
  /** @type {string} The disposition type */
  this.type = type;
  /** @type {object} Parameter name-value pairs */
  this.parameters = parameters;
}

Unicode and Encoding Support

The library automatically handles Unicode filenames according to RFC 5987:

  • Unicode Detection: Automatically detects when filenames contain non-ISO-8859-1 characters
  • Extended Parameters: Uses filename* parameter with UTF-8 encoding for Unicode filenames
  • Fallback Generation: Automatically generates ISO-8859-1 compatible fallback using filename parameter
  • Charset Support: Supports UTF-8 and ISO-8859-1 charsets in extended parameters
  • Percent Encoding: Properly encodes special characters in extended parameters

Error Handling

The library throws TypeError exceptions for various error conditions:

  • Invalid Arguments: Non-string filename or invalid fallback type
  • Encoding Errors: Fallback string contains non-ISO-8859-1 characters
  • Parse Errors: Malformed header strings, invalid parameter format, duplicate parameters
  • Charset Errors: Unsupported charset in extended field values

Standards Compliance

Content-Disposition follows relevant RFC specifications:

  • RFC 2616: HTTP/1.1 specification for quoted strings and parameter formatting
  • RFC 5987: Character Set and Language Encoding for HTTP Header Field Parameters
  • RFC 6266: Use of the Content-Disposition Header Field in the Hypertext Transfer Protocol (HTTP)

Common Use Cases

const http = require('http');
const fs = require('fs');
const contentDisposition = require('content-disposition');

// File download endpoint
http.createServer((req, res) => {
  const filename = 'quarterly-report.pdf';
  
  res.setHeader('Content-Type', 'application/pdf');
  res.setHeader('Content-Disposition', contentDisposition(filename));
  
  const stream = fs.createReadStream('/path/to/file.pdf');
  stream.pipe(res);
});

// Express.js middleware
app.get('/download/:filename', (req, res) => {
  const filename = req.params.filename;
  
  // Validate and sanitize filename
  res.setHeader('Content-Disposition', contentDisposition(filename));
  res.sendFile(path.join(__dirname, 'uploads', filename));
});

// Parse uploaded file headers
app.post('/upload', (req, res) => {
  const disposition = req.headers['content-disposition'];
  if (disposition) {
    const parsed = contentDisposition.parse(disposition);
    console.log('Upload filename:', parsed.parameters.filename);
  }
});

docs

index.md

tile.json