Table of Contents
grammar
parameter
Example 4
Using the download attribute of tag to create file download button using JavaScript.
Use window.open() method
Using the window.open() method to create a file download button using JavaScript.
Get user input, create a file using that input, and allow the user to download the file
algorithm
Create the file from the custom text and allow users to download that file
Use axios library to create a download file button
Using the axios library to trigger a download file.
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?

Sep 12, 2023 pm 12:49 PM
javascript Download Document html button

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.

1

<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.

1

2

3

4

5

6

7

8

9

10

<html>

   <body>

      <h3 id="Using-the-i-download-attribute-of-a-tag-i-to-create-file-download-button-using-JavaScript"> 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.

1

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.

1

2

3

4

5

6

7

8

9

10

11

12

<html>

<body>

   <h3 id="Using-the-i-window-open-method-i-to-create-a-file-download-button-using-JavaScript"> 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.

1

2

3

4

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

<html>

<body>

   <h3 id="Create-the-file-from-the-custom-text-and-allow-users-to-download-that-file"> 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.

1

2

3

4

5

6

7

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

<html>

<head>

   <script src = "https://cdnjs.cloudflare.com/ajax/libs/axios/1.3.1/axios.min.js"> </script>

</head>

<body>

   <h3 id="Using-the-i-axios-library-i-to-trigger-a-download-file"> 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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Python opening operation after downloading the file Python opening operation after downloading the file Apr 03, 2024 pm 03:39 PM

Python provides the following options to open downloaded files: open() function: open the file using the specified path and mode (such as 'r', 'w', 'a'). Requests library: Use its download() method to automatically assign a name and open the file directly. Pathlib library: Use write_bytes() and read_text() methods to write and read file contents.

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

See all articles