Adds reusable function blobDownload

This commit is contained in:
leekelleher
2024-04-02 10:17:07 +01:00
parent 86df2e9481
commit d96dedc7fd
2 changed files with 26 additions and 0 deletions

View File

@@ -0,0 +1,25 @@
/**
* Triggers a client-side download of a file, using a `Blob` object.
* To do this, a temporary anchor element is created, appended to the document body,
* immediate triggered to download, then removed from the document body.
*
* @param {any} data - The data to be downloaded.
* @param {string} filename - The name of the file to be downloaded.
* @param {string} mimeType - The MIME type of the file to be downloaded.
* @returns {void}
*
* @example
* blobDownload(data, 'package.xml', 'text/xml');
*/
export const blobDownload = (data: any, filename: string, mimeType: string) => {
const blob = new Blob([data], { type: mimeType });
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.style.display = 'none';
document.body.appendChild(a);
a.dispatchEvent(new MouseEvent('click'));
a.remove();
window.URL.revokeObjectURL(url);
};

View File

@@ -14,3 +14,4 @@ export * from './type/diff.type.js';
export * from './string/to-camel-case/to-camel-case.function.js';
export * from './string/from-camel-case.function.js';
export * from './debounce/debounce.function.js';
export * from './download/blob-download.function.js';