All files / src/util download.ts

92.3% Statements 12/13
100% Branches 8/8
66.66% Functions 2/3
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30    24x 24x 24x 24x 24x     24x                 32x 32x 2x 2x         31x 32x    
/** Save `blob` as a file the browser downloads, then release it. */
export function saveBlob(blob: Blob, filename: string): void {
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = filename;
  a.click();
  // Revoked on the next tick: some browsers start the download
  // asynchronously and would find the URL already gone.
  setTimeout(() => URL.revokeObjectURL(url), 0);
}
 
/** The filename in a `Content-Disposition` header, if it names one: the
 *  exact name (`filename*`, RFC 6266) when the header carries it, else the
 *  plain `filename`, which a non-ASCII name only approximates. */
export function dispositionFilename(
  header: string | undefined | null,
): string | null {
  const exact = /filename\*=UTF-8''([^;\s]+)/i.exec(header ?? "");
  if (exact) {
    try {
      return decodeURIComponent(exact[1]);
    } catch {
      // A malformed encoding falls back to the plain name.
    }
  }
  const match = /filename="?([^";]+)"?/i.exec(header ?? "");
  return match ? match[1] : null;
}