-
-
Save foxbit19/3abd2cfd85eba09ea5d9c6d67f6d3dd5 to your computer and use it in GitHub Desktop.
Generate URL from blob and force file download in JavaScript
This file contains hidden or 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
/** | |
* Generates an URL from blob data | |
* @param blob data to use for URL generation | |
*/ | |
function generateURL(blob) { | |
return URL.createObjectURL(blob); | |
} | |
/** | |
* Dispose URL previusly generated to avoid memory issues. | |
* @see https://developer.mozilla.org/en-US/docs/Web/API/URL/createObjectURL#memory_management | |
* @param url to dispose | |
*/ | |
function disposeURL(url) { | |
URL.revokeObjectURL(url) | |
} | |
/** | |
* Force a file to download starting from blob data | |
* @param name of file to download | |
* @param blob file data | |
*/ | |
function forceDownload(name, blob) { | |
const anchor = document.createElement('a'); | |
anchor.href = generateURL(blob); | |
anchor.download = name; | |
document.body.appendChild(anchor); | |
anchor.click(); | |
document.body.removeChild(anchor); | |
disposeURL(blob); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment