Yevhen Klymentiev
dark
light
console
darkness
y.klymentiev@gmail.com
Reusable Snippets|Practical utility code for everyday use — custom-built and ready to share

downloadBlob

Triggers download of a Blob or File in the browser.

TypeScript
Copied!
1/**
2 * Triggers download of a Blob or File in the browser.
3 *
4 * @param blob - The Blob or File object to download.
5 * @param filename - The name for the downloaded file.
6 */
7export function downloadBlob(blob: Blob, filename: string): void {
8  const url = URL.createObjectURL(blob);
9  const a = document.createElement('a');
10  a.href = url;
11  a.download = filename;
12  a.style.display = 'none';
13
14  document.body.appendChild(a);
15  a.click();
16  document.body.removeChild(a);
17
18  URL.revokeObjectURL(url);
19}
  • Browser-Native File Download

    Leverages standard browser APIs (URL.createObjectURL, <a download>) for a consistent, plugin-free download experience.

  • Supports Blob and File Types

    Works with any Blob or File object, enabling downloads of binary data, generated content, or uploaded files.

  • Memory Management Friendly

    Calls URL.revokeObjectURL to release the object URL after use, avoiding memory leaks in long-running apps.

  • No User Interaction Required

    Programmatically initiates download without needing user clicks beyond the initial trigger.

Tests | Examples

TypeScript
Copied!
1test('downloadBlob - creates anchor and triggers download', () => {
2  const blob = new Blob(['Hello, world!'], { type: 'text/plain' });
3  const mockCreateObjectURL = vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:url');
4  const mockRevokeObjectURL = vi.spyOn(URL, 'revokeObjectURL');
5
6  const appendChild = vi.spyOn(document.body, 'appendChild');
7  const removeChild = vi.spyOn(document.body, 'removeChild');
8
9  downloadBlob(blob, 'test.txt');
10
11  expect(mockCreateObjectURL).toHaveBeenCalledWith(blob);
12  expect(mockRevokeObjectURL).toHaveBeenCalledWith('blob:url');
13  expect(appendChild).toHaveBeenCalled();
14  expect(removeChild).toHaveBeenCalled();
15
16  mockCreateObjectURL.mockRestore();
17  mockRevokeObjectURL.mockRestore();
18});

Common Use Cases

  • Exporting Generated Content

    Save dynamic reports, charts, or data exports (e.g., CSV, PDF, JSON) created in the browser.

  • Downloading Uploaded Files

    Allow users to re-download previously uploaded or edited files (e.g., preview-and-save workflows).

  • Saving Canvas or Media Output

    Trigger download of canvas-rendered images, video blobs, or recorded media streams.

  • Backup and Offline Data

    Enable users to download local backups or settings in browser-based tools.

  • File Transformation Tools

    Output converted file formats (e.g., markdown to HTML, image compression) as downloadable blobs.

Codebase: Utilities -> Browser & DOM -> downloadBlob | Yevhen Klymentiev