Created
March 23, 2021 23:11
-
-
Save Luke-SNAW/7615865c097c8608697ea234f09e7de8 to your computer and use it in GitHub Desktop.
[How trigger file downloads with JavaScript]
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
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