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

downloadFromURL

Downloads a file from the given URL and saves it with the specified filename.

TypeScript
Copied!
1/**
2 * Downloads a file from the given URL and saves it with the specified filename.
3 *
4 * @param url - The URL to download the file from.
5 * @param filename - The desired name of the downloaded file.
6 */
7export async function downloadFromURL(url: string, filename: string): Promise<void> {
8  const response = await fetch(url);
9  if (!response.ok) {
10    throw new Error(`Failed to fetch file from ${url}`);
11  }
12
13  const blob = await response.blob();
14  const blobUrl = URL.createObjectURL(blob);
15
16  const link = document.createElement('a');
17  link.href = blobUrl;
18  link.download = filename;
19  document.body.appendChild(link);
20  link.click();
21  document.body.removeChild(link);
22  URL.revokeObjectURL(blobUrl);
23}
  • Supports Custom File Naming

    Allows the developer to specify a filename, improving user experience and download clarity.

  • Safe Resource Cleanup

    Automatically revokes the temporary blob URL to free up memory after download.

  • No External Dependencies

    Fully browser-native; uses built-in APIs like fetch, Blob, and URL.createObjectURL.

  • Handles Binary Content Gracefully

    Capable of downloading any file type (images, PDFs, archives) without content-type issues.

  • Programmatic Triggering

    Initiates the download without requiring a user to click an actual <a> tag manually.

Tests | Examples

TypeScript
Copied!
1beforeEach(() => {
2  global.fetch = jest.fn();
3  URL.createObjectURL = jest.fn(() => 'blob:fake-url');
4  URL.revokeObjectURL = jest.fn();
5  document.body.appendChild = jest.fn();
6  document.body.removeChild = jest.fn();
7});
8
9test('downloadFromURL - successful download triggers link click', async () => {
10  const mockClick = jest.fn();
11  const mockBlob = new Blob(['test']);
12
13  (fetch as jest.Mock).mockResolvedValue({
14    ok: true,
15    blob: () => Promise.resolve(mockBlob),
16  });
17
18  const link = { click: mockClick } as unknown as HTMLAnchorElement;
19  document.createElement = jest.fn(() => link);
20
21  await downloadFromURL('https://example.com/file.txt', 'file.txt');
22
23  expect(fetch).toHaveBeenCalledWith('https://example.com/file.txt');
24  expect(URL.createObjectURL).toHaveBeenCalledWith(mockBlob);
25  expect(mockClick).toHaveBeenCalled();
26  expect(document.body.appendChild).toHaveBeenCalledWith(link);
27  expect(document.body.removeChild).toHaveBeenCalledWith(link);
28  expect(URL.revokeObjectURL).toHaveBeenCalledWith('blob:fake-url');
29});
30
31test('downloadFromURL - throws error if fetch fails', async () => {
32  (fetch as jest.Mock).mockResolvedValue({ ok: false });
33
34  await expect(downloadFromURL('https://example.com/bad', 'bad.txt')).rejects.toThrow(
35    'Failed to fetch file from https://example.com/bad'
36  );
37});

Common Use Cases

  • Download Reports or Exports

    Trigger downloads of dynamically generated CSV, PDF, or JSON files.

  • Save Media Assets

    Allow users to download images, videos, or audio files from a known URL.

  • Backup or Export Functionality in Apps

    Let users export settings or data to local storage for backup or migration.

  • Download Resources from APIs

    Fetch and store files delivered through authenticated or pre-signed URLs.

Codebase: Utilities -> Network -> downloadFromURL | Yevhen Klymentiev