Last active
July 20, 2021 12:03
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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