Home > Web Front-end > HTML Tutorial > How to trigger file download when clicking HTML button or JavaScript?

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

王林
Release: 2023-09-12 12:49:02
forward
1287 people have browsed it

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

Nowadays, many applications allow users to upload and download their files. For example, plagiarism detection tools allow users to upload a document file that contains some text. It then checks for plagiarism and generates a report that users can download.

Everyone knows to use input type file to create a file upload button, but few developers know how to use JavaScript/JQuery to create a file download button.

This tutorial will teach various ways to trigger file downloads when an HTML button or JavaScript is clicked.

Use HTML's tag and download attribute to trigger file download when the button is clicked

Whenever we add the download attribute to the tag, we can use the tag as a file download button. We need to pass the URL of the file as the value of the href attribute to allow the user to download a specific file when they click on the link.

grammar

Users can create a file download button using the tag according to the following syntax.

<a href = "file_path" download = "file_name">
Copy after login

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

parameter

  • file_path – This is the path to the file we want the user to download.

Example 1

is translated as:

Example 1

In the example below, we are passing the image URL as the value of the href attribute of the HTML tag. We use the download button as the anchor text for the tag

Whenever the user clicks the button, they can see 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>
Copy after login

Use window.open() method

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

If the open() method cannot open the URL, file download will be triggered.

grammar

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

window.open("file_url")
Copy after login

In the above syntax, we pass 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, the window.open() method triggers file downloading.

<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>
Copy after login

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

This method will allow the user to write text in the input box. After that, using the entered text, we will create a new file and allow the user to download the file.

grammar

Users can create a file with custom text following the following syntax 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(); 
Copy after login

In the above syntax, we encoded the text to append it to the file and created it using the tag.

algorithm

The Chinese translation of

Example 3

is:

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>
Copy after login

Use axios library to create a download file button

axios library allows us to get data from any URL. So we will get the data from any URL or file path and then set that data as the value of the href attribute of the tag. Additionally, we will add the download attribute to the tag using the setAttribute() method and trigger the file download using the click() method.

grammar

Users can use axios and JavaScript to trigger file downloads according to the following syntax.

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]));
Copy after login

In the above syntax, the axios.get() method allows us to get data from the file_path stored in the results variable. After that, we use the new Blob() constructor to convert the data into a Blob object.

The Chinese translation of

Example 4

is:

Example 4

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

Afterwards, we clicked on the element via 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>
Copy after login

The above is the detailed content of How to trigger file download when clicking HTML button or JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template