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.
- Author: Ahmed Bouchefra Follow @ahmedbouchefra
-
Date:
Related posts
Convert a string to a number in JavaScript How to download a file in JavaScript JavaScript Blobs and object URLs Use JavaScript's Object.entries() for iterating over an object's properties How to get current time zone in JavaScript How to add days to dates in JavaScript Convert String To Number/Array In JavaScript with React Hooks/Vue.JS Examples JavaScript/Node Top-lavel Await Example [TIP] $(document).ready() vs window.onload() vs $(window).load() [TIP] Pure JavaScript equivalent or alternative to jquery.ready()