Skip to content

Instantly share code, notes, and snippets.

@moekhalil
Last active September 6, 2022 12:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moekhalil/2900bbc68aa474f031e76f22e456db97 to your computer and use it in GitHub Desktop.
Save moekhalil/2900bbc68aa474f031e76f22e456db97 to your computer and use it in GitHub Desktop.
Save any file at a url with a provided filename
// Created By : moe | mail is πšπš‘πšžπš‹-𝚊𝚝-πš–πš”πš‘πšŠπš•πš’πš•.πš˜πš›πš
// Uploaded To : https://gist.github.com/moekhalil
// Uploaded Date: 09/06/2022
// Notes : Save any file at a url with a provided filename.
// : Unlike download attribute, this even works with cross-origin urls
const downloadURLAsFilename = async ({ url, fileName }) => {
const mediaItem = await fetch(url);
const mediaBlob = await mediaItem.blob();
const fileBlobURL = URL.createObjectURL(mediaBlob);
const domAnchorElement = document.createElement('a');
domAnchorElement.setAttribute("download", fileName);
domAnchorElement.setAttribute("href", fileBlobURL);;
domAnchorElement.addEventListener("click", () => {
setTimeout(() => {
URL.revokeObjectURL(fileBlobURL);
domAnchorElement.remove();
}, 500);
});
document.body.append(domAnchorElement);
domAnchorElement.click();
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment