diff --git a/src/Umbraco.Web.UI.Client/src/packages/core/utils/download/blob-download.function.ts b/src/Umbraco.Web.UI.Client/src/packages/core/utils/download/blob-download.function.ts new file mode 100644 index 0000000000..f4371b4ac0 --- /dev/null +++ b/src/Umbraco.Web.UI.Client/src/packages/core/utils/download/blob-download.function.ts @@ -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); +}; diff --git a/src/Umbraco.Web.UI.Client/src/packages/core/utils/index.ts b/src/Umbraco.Web.UI.Client/src/packages/core/utils/index.ts index 0fc65a99ab..3782c9eb05 100644 --- a/src/Umbraco.Web.UI.Client/src/packages/core/utils/index.ts +++ b/src/Umbraco.Web.UI.Client/src/packages/core/utils/index.ts @@ -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';