dvContentDisposition function

String dvContentDisposition(
  1. String fileName
)

A content-disposition header that downloads a file named fileName.

RFC 6266: a quoted ASCII filename for clients that read only that, and filename* in UTF-8 (RFC 8187) carrying the real name. Control characters become _ in both, so a name can never end the header and start another; a quote or backslash is escaped inside the quoted form. An empty name is download.

Implementation

String dvContentDisposition(String fileName) {
  final String safe = String.fromCharCodes(fileName.runes.map(
      (int rune) => rune < 0x20 || rune == 0x7f ? 0x5f : rune));
  final String name = safe.isEmpty ? 'download' : safe;
  final StringBuffer ascii = StringBuffer();
  for (final int rune in name.runes) {
    if (rune > 0x7e) {
      ascii.write('_');
    } else if (rune == 0x22 || rune == 0x5c) {
      ascii
        ..write(r'\')
        ..writeCharCode(rune);
    } else {
      ascii.writeCharCode(rune);
    }
  }
  const String attrChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
      '0123456789!#\$&+-.^_`|~';
  final StringBuffer encoded = StringBuffer();
  for (final int byte in utf8.encode(name)) {
    if (byte < 0x80 && attrChars.contains(String.fromCharCode(byte))) {
      encoded.writeCharCode(byte);
    } else {
      encoded.write('%${byte.toRadixString(16).toUpperCase().padLeft(2, '0')}');
    }
  }
  return 'attachment; filename="$ascii"; filename*=UTF-8\'\'$encoded';
}