content-disposition

repository·master·Indexed 42 days ago

https://github.com/jshttp/content-disposition

A utility for creating and parsing HTTP Content-Disposition headers, version 3.0.0. It provides robust support for Unicode filenames via RFC 5987 and multipart/form-data compatibility. Key functions include create() for generating header values, parse() for converting header strings into JavaScript objects, and format() for converting objects back into header strings.

Tokens
1.7K
Snippets
11
Records
11
Agent score
4%

What's inside content-disposition

  1. Example: Send a file for download in Node.js

    master

    This example demonstrates how to use content-disposition to set the appropriate headers when serving a file via a Node.js HTTP server.

    import fs from 'node:fs';
    import http from 'node:http';
    import { create } from 'content-disposition';
    import onFinished from 'on-finished';
    
    const filePath = '/path/to/public/plans.pdf';
    
    http.createServer(function onRequest(req, res) {
      // set headers
      res.setHeader('Content-Type', 'application/pdf');
      res.setHeader('Content-Disposition', create(filePath));
    
      // send file
      const stream = fs.createReadStream(filePath);
      stream.pipe(res);
      onFinished(res, function () {
        stream.destroy();
      });
    });
  2. Parse a Content-Disposition header with parse()

    master

    Use parse(string, options) to convert a Content-Disposition header string into a JavaScript object. This function automatically handles extended (Unicode) parameters by decoding them and providing them under the standard parameter name.

    Returns an object with:

    • type: The disposition type (lowercase, e.g., 'attachment').
    • parameters: An object containing the parameters (keys are lowercase; extended versions replace non-extended versions).
    import { parse } from 'content-disposition';
    
    const disposition = parse(
      'attachment; filename="EURO rates.txt"; filename*=UTF-8\"\''%e2%82%ac%20rates.txt',
    );
    // Result: { type: 'attachment', parameters: { filename: '€ rates.txt' } }
  3. Create a Content-Disposition header with create()

    master

    Use create(filename, options) to generate an attachment Content-Disposition header value. If you want to specify options but do not want a filename, set filename to undefined.

    Note: HTTP headers use the ISO-8859-1 character set. If you are setting this header through a method other than Node.js's res.setHeader, you may need to specify 'binary' encoding.

    import { create } from 'content-disposition';
    
    res.setHeader('Content-Disposition', create('∫ maths.pdf'));
  4. Format a Content-Disposition object with format()

    master

    Use format(obj, options) to convert a JavaScript object into a Content-Disposition header string. It automatically handles extended (Unicode) parameters.

    import { format } from 'content-disposition';
    
    const disposition = format({
      type: 'attachment',
      parameters: {
        filename: '€ rates.txt',
      },
    });
    // Result: 'attachment; filename*=UTF-8\"\''%E2%82%AC%20rates.txt'
  5. Decode RFC 8187 field values with decodeExtended()

    master

    Use decodeExtended(str) to decode a string that has been encoded using the RFC 8187 format. It supports utf-8 and iso-8859-1 charsets. If the string is malformed or the charset is unsupported, it returns undefined.

    import { decodeExtended } from 'content-disposition';
    
    const decoded = decodeExtended("UTF-8''%E6%B5%8B");
    // Output: '测试'
    
    const isoDecoded = decodeExtended("iso-8859-1''%E9");
    // Output: 'é'
  6. Encode Unicode strings for HTTP with encodeExtended()

    master

    Use encodeExtended(str) to encode a string using the RFC 8187 format (e.g., UTF-8''...). This is the standard way to represent non-US-ASCII characters in Content-Disposition parameters like filename*.

    import { encodeExtended } from 'content-disposition';
    
    const encoded = encodeExtended('🚀');
    // Output: "UTF-8''%F0%9F%9A%80"
  7. Configure format() options

    master

    The FormatOptions object allows you to customize how the object is formatted into a string:

    • extended (boolean, optional): Whether to use extended parameter encoding for non-ISO-8859-1 strings. If false, an error is thrown when attempting to format such strings. Defaults to true.
    • multipart (boolean, optional): Whether to format parameters as sent by browsers in multipart/form-data. Defaults to false.
    interface FormatOptions {
      extended?: boolean;
      multipart?: boolean;
    }
  8. Configure create() options

    master

    The CreateOptions object allows you to customize how the header is generated:

    • type (string, optional): The Content-Disposition type. Defaults to 'attachment'.
    • fallback (string | boolean, optional):
      • If true (default): Non-US-ASCII characters in the filename are replaced with ? for the standard filename parameter, while the filename* parameter is generated using encodeExtended.
      • If a string: This string is used as the filename parameter. If it is also used as the base for filename*, it will be encoded.
      • If false: No fallback filename is generated; only filename* will be present if the filename is non-ASCII.
    interface CreateOptions {
      type?: string;
      fallback?: string | boolean;
    }
  9. Configure parse() options

    master

    The ParseOptions object allows you to customize how the header is parsed:

    • extended (boolean, optional): Whether to decode RFC 8187 encoded parameters (e.g., filename*). Defaults to true.
    • multipart (boolean, optional): Whether to parse parameters as sent by browsers in multipart/form-data. Defaults to false.
    interface ParseOptions {
      extended?: boolean;
      multipart?: boolean;
    }