Skip to content

Instantly share code, notes, and snippets.

@khannurien
Last active July 20, 2021 12:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khannurien/54b02f9c62ae0e4f0453efc2affc5154 to your computer and use it in GitHub Desktop.
Save khannurien/54b02f9c62ae0e4f0453efc2affc5154 to your computer and use it in GitHub Desktop.
Create a pseudo-link to a file in order to trigger browser prompt for file download.
/**
* Download a file from a Blob with explicitly set MIME type.
* @param fileBlob The input Blob.
* @param mimeType A string representing a conform MIME type (see RFC 6838).
* @param outName A string for the downloaded file name.
*/
export const downloadFile = (fileBlob: Blob, mimeType: string, outName: string): void => {
// explicitly set blob mime-type
const blob = new Blob([fileBlob], { type: mimeType });
// IE compatibility
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob);
return;
}
//const createObjectURL = (window.URL || window.webkitURL || {}).createObjectURL || function(){};
const download = window.URL.createObjectURL(blob);
const link = document.createElement('a');
link.setAttribute('href', download);
link.setAttribute('download', outName);
link.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true, view: window }));
// avoid memory leak
setTimeout(function () {
// for Firefox it is necessary to delay revoking the ObjectURL
window.URL.revokeObjectURL(download);
link.remove();
}, 100);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment