How to download a file in JavaScript

How to download a file in JavaScript

In this article, we'll see how to download files in JavaScript. We have many ways to download a file in JavaScript. Developers can make use of the anchor's download attribute or programmatically create an object URL in JavaScript.

Using the HTML5 download attribute

You can use the download to instruct the browser to download the requested URL rather than navigating to it.

Here is an example:

<a href="book.pdf" download>Download the file</a>

You can also provide a value for the download attribute that will be used as the file name. If the value is not provided, the filename is used:

<a href="book.pdf" download="yourbook.pdf">Download file</a>

As was just demonstrated, the download attribute is the most straightforward means by which a file can be downloaded in a web browser. Since it is already built into the HTML DOM, you don't even need JavaScript for this. However, older browsers won't be able to use the download attribute.

  • Date: