How to trigger a file download when clicking an HTML button or JavaScript?


Nowadays, many applications allow their users to upload and download files. For example, plagiarism checker tools allow users to upload a document file with some text. After that, it checks for plagiarism and generates a report, and users can download it.

Everyone knows to create an upload file button using the input type file, but there are few developers who know to create a file download button using JavaScript/ JQuery.

This tutorial will teach various approaches to trigger a file download when clicking an HTML button or JavaScript.

Use the download attribute with HTML <a> tag to trigger a file download on the button click

Whenever we add the download attribute to the <a> tag, we can make the <a> tag work as a file download button. We need to pass the file url as a value of the href attribute to allow users to download any particular file on the link click.

Syntax

Users can follow the syntax below to use the <a> tag to create a file download button.

<a href = "file_path" download = "file_name">

In the above syntax, we have added the download attribute and file name as a value of the download attribute.

Parameters

  • file_path – It is a file path that we wanted users to download.

Example 1

In the example below, we have taken the image URL and passed it as a value of the href attribute of the HTML <a> tag. We have used the download button as an anchor text of <a> tag.

Whenever users click the button, they can see that it triggers the file download.

<html>
   <body>
      <h3> Using the <i> download attribute of <a> tag </i> to create file download button using JavaScript. </h3>
      <p> Click the below button to download the image file </p>
      <a href = "https://images.pexels.com/photos/268533/pexels-photo-268533.jpeg?cs=srgb&dl=pexels-pixabay-268533.jpg&fm=jpg"
      Download = "test_image">
         <button type = "button"> Download </button>
      </a>
   </body>
</html>

Use the window.open() method

The window.open() method opens a URL in the new tab. We can pass the URL as a parameter of the open() method.

If the open() method can’t open the URL, it triggers the file download.

Syntax

Users can follow the syntax below to use the window.open() method to create a file download button.

window.open("file_url")

In the above syntax, we have passed the file URL as a parameter of the window.open() method.

Example 2

In the example below, whenever the user clicks the button, it triggers the downloadFile() function. In the downloadFile() function window.open() method triggers the file download.

<html>
<body>
   <h3> Using the <i> window.open() method </i> to create a file download button using JavaScript. </h3>
   <p> Click the below button to download the image file </p>
   <button type = "button" onclick = "downloadFile()"> Download </button>
</body>
   <script>
      function downloadFile() {
         window.open("https://images.pexels.com/photos/268533/pexels-photo-268533.jpeg?cs=srgb&dl=pexels-pixabay-268533.jpg&fm=jpg")
      }
   </script>
</html>

Take user input, create a file using that and allow users to download the file

This approach will allow users to write texts in the input field. After that, using the input texts, we will create a new file and allow users to download that file.

Syntax

Users can follow the syntax below to create a file from the custom text and allow users to download it.

var hidden_a = document.createElement('a'); 
hidden_a.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(texts)); 
hidden_a.setAttribute('download', "text_file"); 
document.body.appendChild(hidden_a); hidden_a.click(); 

In the above syntax, we encoded the text to append it to the file and used <a> tag to create it.

Algorithm

  • Step 1 − Get the texts from the input by accessing the HTML input.

  • Step 2 − Create a custom HTML <a> tag using JavaScript createElement() method.

  • Step 3 − Use the setAttribute() method, and set the href attribute for the hidden_a HTML element. Use the encoded texts as a value of the href attribute.

  • Step 4 − Again, use the setAttribute() method and set the download attribute with the download file name value to the hidden_a element.

  • Step 5 − Append the hidden_a element to the body.

  • Step 6 − Use the click() method to trigger a click on the hidden_a element. When it invokes the click() method, it starts the download.

  • Step 7 − Remove the hidden_a element from the document body using the removeChild() method.

Example 3

In the example below, users can enter any custom text in the input field and click the button to trigger file download using JavaScript. We have implemented the above algorithm to trigger a file download.

<html>
<body>
   <h3> Create the file from the custom text and allow users to download that file </h3>
   <p> Click the below button to download the file with custom text. </p>
   <input type = "text" id = "file_text" value = "Entetr some text here.">
   <button type = "button" onclick = "startDownload()"> Download </button>
</body>
   <script>
      function startDownload() {
         // access the text from the input field
         let user_input = document.getElementById('file_text');
         let texts = user_input.value;
         
         // Create dummy <a> element using JavaScript.
         var hidden_a = document.createElement('a');
         
         // add texts as a href of <a> element after encoding.
         hidden_a.setAttribute('href', 'data:text/plain;charset=utf-8, '+ encodeURIComponent(texts));
         
         // also set the value of the download attribute
         hidden_a.setAttribute('download', "text_file");
         document.body.appendChild(hidden_a);
         
         // click the link element
         hidden_a.click();
         document.body.removeChild(hidden_a);
      }
   </script>
</html>

Use the axios library to create a download file button

The axios library allows us to fetch data from any URL. So, we will fetch data from any URL or file path, and after that, we will set that data as a value of the href attribute of <a> tag. Also, we will add a download attribute to the <a> tag using the setAttribute() method and trigger a click() method to start the file download.

Syntax

Users can follow the syntax below to use axios to trigger a file download using JavaScript.

let results = await axios({
   url: 'file_path',
   method: 'GET',
   responseType: 'blob'
})
// use results as a value of href attribute of <a> tag to download file
hidden_a.href = window.URL.createObjectURL(new Blob([results.data]));

In the above syntax, axios.get() method allows us to fetch data from the file_path stored in the results variable. After that, we converted the data to the Bolb object using the new Blob() constructor.

Example 4

In the example below, we fetch data from the URL using axios, convert it to the Blob object, and set it as a value of the href attribute.

After that, we clicked the <a> element from JavaScript to trigger the file download.

<html>
<head>
   <script src = "https://cdnjs.cloudflare.com/ajax/libs/axios/1.3.1/axios.min.js"> </script>
</head>
<body>
   <h3> Using the <i> axios library </i> to trigger a download file. </h3>
   <p> Click the below button to download the file with custom text. </p>
   <button type = "button" onclick = "startDownload()"> Download </button>
</body>
   <script>
      async function startDownload() {
         // get data using axios
         let results = await axios({
            url: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTZ4gbghQxKQ00p3xIvyMBXBgGmChzLSh1VQId1oyhYrgir1bkn812dc1LwOgnajgWd-Yo&usqp=CAU',
            method: 'GET',
            responseType: 'blob'
         })
         let hidden_a = document.createElement('a');
         hidden_a.href = window.URL.createObjectURL(new Blob([results.data]));
         hidden_a.setAttribute('download', 'download_image.jpg');
         document.body.appendChild(hidden_a);
         hidden_a.click();
      }
   </script>
</html>

Updated on: 14-Sep-2023

37K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements