How to Download a File using JavaScript
Table of Contents
In this post, we'll learn how you can download a file programmatically in the browser using JavaScript.
To download a file, we can take advantage of several HTML features and use them programmatically to initiate a download a file.
The only thing you'll need is the URL to the file you want to download, and a name for the file.
To take advantage of the fact that links can initiate downloads, let's first create an anchor tag.
JAVASCRIPTconst anchor = document.createElement("a");
Next, we'll set the href attribute to the URL of the file we want to download.
JAVASCRIPTconst anchor = document.createElement("a");
anchor.href = "https://sabe.io/images/saturn.png";
Now, we'll set the download attribute to the name of the file we want to download. This is the magic that makes it a download.
JAVASCRIPTconst anchor = document.createElement("a");
anchor.href = "https://sabe.io/images/saturn.png";
anchor.setAttribute("download", "saturn.png");
Now we just need to click it so it initiates the download.
JAVASCRIPTconst anchor = document.createElement("a");
anchor.href = "https://sabe.io/images/saturn.png";
anchor.setAttribute("download", "saturn.png");
anchor.click();
That's pretty much it. That code should work right away. However, we should turn it into a function so that it can be easily re-used:
JAVASCRIPTconst downloadFile = (url, fileName) => {
const anchor = document.createElement("a");
anchor.href = url;
anchor.setAttribute("download", fileName);
anchor.click();
};
Now, you can just call it like this:
JAVASCRIPTdownloadFile("https://sabe.io/images/saturn.png", "saturn.png");
Conclusion
In this post, we've looked at how you can download a file programmatically in the browser using JavaScript.
Hopefully, this helped you download the file you want to download.
Thanks for reading and happy coding!
- Getting Started with TypeScript
- Create an RSS Reader in Node
- Getting Started with Electron
- How to deploy a PHP app using Docker
- How to deploy a MySQL Server using Docker
- How to deploy an Express app using Docker
- How to Scrape the Web using Node.js and Puppeteer
- Getting Started with Handlebars.js
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting Started with Moment.js
- Getting Started with React
- How To Create a Modal Popup Box with CSS and JavaScript