Open In App
Related Articles

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

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

In today’s digital age, numerous applications offer the feature to upload and download files. For instance, plagiarism checker tools enable users to upload a document file containing text. The tool then checks for plagiarism and generates a report, which can be downloaded by the user.

To trigger a file download on a button click we will use a custom function or HTML 5 download attribute.

Using Download attribute 

The download attribute simply uses an anchor tag to prepare the location of the file that needs to be downloaded. The name of the file can be set using the attribute value name, if not provided then the original filename will be used.

Syntax:

<a download="filename">

// filename attribute specifies the name of the file that will be downloaded.

Example: In this example, we will see the implementation of the above approach with an example.

html

<!DOCTYPE html>
<html>
 
<body>
    <style>
        p {
            color: green;
        }
    </style>
    <p>
        How to trigger a file download when
        clicking an HTML button or JavaScript?
    </p>
    <a href="geeksforgeeks.png" download="GFG">
        <button type="button">Download</button>
    </a>
</body>
 
</html>

                    

Output:

mn

Output

Using a custom javascript function 

First create a textarea to capture user input, where the text content is intended for the downloadable file Now :

  • Dynamically generate an anchor (<a>) tag using JavaScript’s createElement property, setting attributes like download and href for file download.
  • Use encodeURIComponent to encode special characters in the text content, ensuring proper formatting in the URI.
  • Simulate a click event on the anchor element using the click() method to initiate the file download, triggered by a button click or another user action.

Example: In this example, we will see the implementation of the above approach with an example.

html

<!DOCTYPE html>
<html>
 
<head>
    <title>
        GeeksforGeeks
    </title>
</head>
 
<body>
    <style>
        p {
            color: green;
        }
    </style>
    <p>
        How to trigger a file download when
        clicking an HTML button or JavaScript?
    <p>
        <textarea id="text">
             Welcome to GeeksforGeeks
         </textarea>
        <br />
        <input type="button" id="btn" value="Download" />
        <script>
            function download(file, text) {
 
                //creating an invisible element
 
                var element = document.createElement('a');
                element.setAttribute('href',
                    'data:text/plain;charset=utf-8, '
                    + encodeURIComponent(text));
                element.setAttribute('download', file);
                document.body.appendChild(element);
                element.click();
 
                document.body.removeChild(element);
            }
 
            // Start file download.
 
            document.getElementById("btn")
                .addEventListener("click", function () {
                    var text =
                            document.getElementById("text").value;
                    var filename = "GFG.txt";
 
                    download(filename, text);
                }, false);
        </script>
</body>
 
</html>

                    

Output: 


ax

Output


Using a custom javascript function with Axios Library

Utilize a custom JavaScript function integrated with the Axios library to make asynchronous HTTP requests, facilitating efficient handling of data from external APIs. Axios simplifies AJAX calls, providing promise-based approach for handling responses in web applications.

Example: In this example, we will see the implementation of the above approach with an example.

html

<!DOCTYPE html>
<!DOCTYPE html>
<html>
 
<head>
    <title>Download Images using Axios</title>
    <style>
        .scroll {
            height: 1000px;
            background-color: white;
        }
    </style>
</head>
 
<body>
    <p id="dest">
    <h1 style="color: green">
        GeeksforGeeks
    </h1>
    </p>
    <button onclick="download()">
        Download Image
    </button>
    <p class="scroll">
        By clicking the download button
        will generate a random image.
    </p>
</body>
</script>
<script>
    function download() {
        axios({
            url: 'https://source.unsplash.com/random/500x500',
            method: 'GET',
            responseType: 'blob'
        })
            .then((response) => {
                const url = window.URL
                    .createObjectURL(new Blob([response.data]));
                const link = document.createElement('a');
                link.href = url;
                link.setAttribute('download', 'image.jpg');
                document.body.appendChild(link);
                link.click();
            })
    }
 
</script>
 
</html>
 
</html>

                    

Output: 

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.



Last Updated : 18 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads