Forked from philipstanislaus/gist:c7de1f43b52531001412
Last active
May 30, 2024 02:50
-
-
Save ppcamp/874b1565a8d6f3ed9ecc233d09b64865 to your computer and use it in GitHub Desktop.
Save a blob (object generated in UI) locally as a file
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
/** | |
* Saves a Blob object as a file with the specified filename. | |
* | |
* @param {Blob} blob - The Blob object to be saved. | |
* @param {String} filename - The desired filename for the saved file. | |
* @example | |
* const foo = ` | |
* NAME;DESCR | |
* Foo;desc1 | |
* bar;desc2 | |
* `; | |
* const blob = new Blob([ foo ], { type: "text/csv" }); | |
* saveBlob(blob,"file.csv"); | |
* | |
*/ | |
const saveBlob = (blob, filename) => { | |
const fragment = document.createDocumentFragment(); | |
const a = document.createElement("a"); | |
// a.style.display = "none"; | |
fragment.appendChild(a); | |
const url = window.URL.createObjectURL(blob); | |
a.href = url; | |
a.download = filename; | |
a.click(); | |
window.URL.revokeObjectURL(url); | |
fragment.removeChild(a); | |
}; |
fetch('blob:https://some.blob.url').then((response) => response.blob().then((b) => saveBlob(b, 'file.ext')));
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://developer.mozilla.org/en-US/docs/Web/API/Document/createDocumentFragment