Skip to content

API Reference


API Reference / @dasch-ng/web-utils / download

Function: download()

download(data, filename, type?): Promise<unknown>

Defined in: download.ts:29

Triggers a browser download for the given data.

This function creates a temporary anchor element with a Blob URL, programmatically clicks it to trigger the download, and automatically cleans up the object URL and DOM element after the download starts.

Parameters

data

string | Blob

The data to download, either as a string or Blob

filename

string

The name of the file to be downloaded

type?

string

Optional MIME type for the Blob (e.g., 'text/plain', 'application/json')

Returns

Promise<unknown>

A Promise that resolves when the download has been triggered

Example

typescript
// Download a text file
await download('Hello, World!', 'greeting.txt', 'text/plain');

// Download JSON data
const data = { name: 'John', age: 30 };
await download(JSON.stringify(data, null, 2), 'data.json', 'application/json');

// Download a Blob (e.g., an image)
const blob = await convertSvgToImage(svgString);
if (blob) {
  await download(blob, 'image.png', 'image/png');
}

Released under the MIT License.