Sometimes, we want to download data URL file with JavaScript.
In this article, we’ll look at how to download data URL file with JavaScript.
How to download data URL file with JavaScript?
To download data URL file with JavaScript, we can create an anchor element that links to the file.
And then we call click
to click the link.
For instance, we write
const download = (dataUrl, filename) => {
const link = document.createElement("a");
link.href = dataUrl;
link.download = filename;
link.click();
};
download("data:text/html,HelloWorld!", "helloWorld.txt");
to create the download
function that creates an anchor element with createElement
.
Then we set its href
attribute to dataUrl
.
And we set the download
attribute to the file name of the downloaded file.
Then we call click
to download the file.
Conclusion
To download data URL file with JavaScript, we can create an anchor element that links to the file.
And then we call click
to click the link.