Skip to main content
@spa-tools/utilities

downloadFile()

The downloadFile() takes content and programmatically downloads it from within the user's browser.

Usage

import { downloadFile } from '@spa-tools/utilities';

// simplest usage where provided text content is downloaded as a text file
downloadFile('Hello, World!', 'hello.txt', 'text');

// downloading a file via a URL is also pretty simple
downloadFile(
'https://example-files.online-convert.com/document/txt/example.txt',
'downloaded-example-text-file.txt',
'url'
);

// downloading a blob is also a snap, especially if
// you already have the blob in-hand
const imageResponse = await fetch(
'https://fastly.picsum.photos/id/28/4928/3264.jpg?hmac=GnYF-RnBUg44PFfU5pcw_Qs0ReOyStdnZ8MtQWJqTfA'
);
const imageBlob = await imageResponse.blob();
downloadFile(imageBlob, 'stream-landscape.jpg', 'blob');

Arguments

NameTypeRequired?DefaultDescription
sourcestring[] | Blobyes-The file's source to download.
fileNamestringyes-The name to be used for the downloaded file
type'blob' | 'text' | 'url'yes-Determines the source mechanism for downloaded file. If 'blob' then the source type must be a Blob; otherwise source type will be string