Download a file using JavaScript
📅October 19, 2021
Today we will show you how to download a file using JavaScript. Here we will give you the JavaScript method to download the file from the URL.
Checkout more articles on JavaScript
- Split an array into chunks in JavaScript
- Verify an image URL in JavaScript
- How to get the window size in JavaScript
- 7 JavaScript One-Liners that you should know
- Add days to a date in JavaScript
Let’s assume that we have an download URL and filename to download the file from the URL. So we will generate `a` tag and trigger the click event to download the file.
function download(fileUrl, fileName) {
var a = document.createElement("a");
a.href = fileUrl;
a.setAttribute("download", fileName);
a.click();
}
download("https://DOMAIN.COM/FILE_NAME.txt", "FILE_NAME.txt");
Note: The HTML’s `download` attribute is used to download a file when clicking on the link (instead of navigating to the file).
I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂