Skip to content

Instantly share code, notes, and snippets.

@foxbit19
Forked from jmcarp/forceDownload.js
Last active March 16, 2021 14:53
Show Gist options
  • Save foxbit19/3abd2cfd85eba09ea5d9c6d67f6d3dd5 to your computer and use it in GitHub Desktop.
Save foxbit19/3abd2cfd85eba09ea5d9c6d67f6d3dd5 to your computer and use it in GitHub Desktop.
Generate URL from blob and force file download in JavaScript
/**
* 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