Skip to content

Instantly share code, notes, and snippets.

@Luke-SNAW
Created March 23, 2021 23:11
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 Luke-SNAW/7615865c097c8608697ea234f09e7de8 to your computer and use it in GitHub Desktop.
Save Luke-SNAW/7615865c097c8608697ea234f09e7de8 to your computer and use it in GitHub Desktop.
[How trigger file downloads with JavaScript]
function downloadFile(file) {
// Create a link and set the URL using `createObjectURL`
const link = document.createElement("a");
link.style.display = "none";
link.href = URL.createObjectURL(file);
link.download = file.name;
// It needs to be added to the DOM so it can be clicked
document.body.appendChild(link);
link.click();
// To make this work on Firefox we need to wait
// a little while before removing it.
setTimeout(() => {
URL.revokeObjectURL(link.href);
link.parentNode.removeChild(link);
}, 0);
}
// Dynamically create a File
const myFile = new File([`${new Date()}: Meow!`], "my-cat.txt");
// Download it using our function
downloadFile(myFile);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment