Last active
September 6, 2022 12:13
-
-
Save moekhalil/2900bbc68aa474f031e76f22e456db97 to your computer and use it in GitHub Desktop.
Save any file at a url with a provided filename
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
// 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