Skip to content

Instantly share code, notes, and snippets.

@ppcamp
Forked from philipstanislaus/gist:c7de1f43b52531001412
Last active May 30, 2024 02:50
Show Gist options
  • Save ppcamp/874b1565a8d6f3ed9ecc233d09b64865 to your computer and use it in GitHub Desktop.
Save ppcamp/874b1565a8d6f3ed9ecc233d09b64865 to your computer and use it in GitHub Desktop.
Save a blob (object generated in UI) locally as a file
/**
* 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);
};
@ppcamp
Copy link
Author

ppcamp commented May 30, 2024

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