downloadFile
Triggers download of a file with specified content and name.
1/**
2 * Triggers download of a file with specified content and name.
3 *
4 * @param content - The file content (as string or Blob).
5 * @param filename - The name of the file to be downloaded.
6 * @param mimeType - Optional MIME type (defaults to 'application/octet-stream').
7 */
8export function downloadFile(
9 content: string | Blob,
10 filename: string,
11 mimeType: string = 'application/octet-stream'
12): void {
13 const blob = content instanceof Blob ? content : new Blob([content], { type: mimeType });
14 const url = URL.createObjectURL(blob);
15
16 const a = document.createElement('a');
17 a.href = url;
18 a.download = filename;
19 a.style.display = 'none';
20
21 document.body.appendChild(a);
22 a.click();
23 document.body.removeChild(a);
24
25 URL.revokeObjectURL(url);
26}
Supports Strings and Blobs
Accepts both raw string data and pre-formed
Blob
objects, offering flexibility in content input.Automatic MIME Type Handling
Defaults to
'application/octet-stream'
, ensuring safe binary fallback if a specific type isn't provided.No Server Required
Enables client-side file generation and download without needing to hit a backend.
Memory Management
Revokes the generated object URL after use to prevent memory leaks.
Cross-Browser Compatibility
Uses anchor element with
download
attribute, which is supported in all modern browsers.
Tests | Examples
1const originalCreateObjectURL = URL.createObjectURL;
2const originalRevokeObjectURL = URL.revokeObjectURL;
3
4beforeEach(() => {
5 URL.createObjectURL = jest.fn(() => 'blob:url');
6 URL.revokeObjectURL = jest.fn();
7 document.body.innerHTML = '';
8});
9
10afterEach(() => {
11 URL.createObjectURL = originalCreateObjectURL;
12 URL.revokeObjectURL = originalRevokeObjectURL;
13 jest.clearAllMocks();
14});
15
16test('creates a download link and clicks it', () => {
17 const clickSpy = jest.fn();
18 document.createElement = jest.fn(() => {
19 const a = document
20 .createElementNS('http://www.w3.org/1999/xhtml', 'a') as HTMLAnchorElement;
21 a.click = clickSpy;
22 return a;
23 }) as any;
24
25 downloadFile('Hello world', 'hello.txt', 'text/plain');
26
27 expect(URL.createObjectURL).toHaveBeenCalled();
28 expect(clickSpy).toHaveBeenCalled();
29 expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:url');
30});
31
32test('accepts Blob as input', () => {
33 const blob = new Blob(['data'], { type: 'text/plain' });
34 downloadFile(blob, 'file.txt');
35 expect(URL.createObjectURL).toHaveBeenCalledWith(blob);
36});
Common Use Cases
Exporting User Data
Allow users to download their form data, reports, or app settings as a JSON or CSV file.
Generating Text-Based Files
Trigger download of logs, notes, or formatted code snippets as
.txt
,.md
, or.html
.Client-Side File Creation
Save files generated in the browser (e.g., screenshots, PDFs, generated documents).
Backup and Restore Features
Provide downloadable backups of local app state or config files.
Offline Content Delivery
Let users download assets or templates for offline use directly from the browser.