Home > Article > Web Front-end > 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.
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.
Users can create a file download button using the tag according to the following syntax.
<a href = "file_path" download = "file_name">
In the above syntax, we added the download attribute and the file name as the value of the download attribute.
file_path – This is the path to the file we want the user to download.
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>
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.
Users can use the window.open() method according to the following syntax to create a file download button.
window.open("file_url")
In the above syntax, we pass the file URL as a parameter of the window.open() method.
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>
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.
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();
In the above syntax, we encoded the text to append it to the file and created it using the tag.
Step One - Get the text by accessing the HTML input.
Step 2 − Create a custom HTML tag using JavaScript createElement() method.
Step 3 − Use the setAttribute() method to set the href attribute for the hidden_a HTML element. Use the encoded text as the value of the href attribute.
Step 4 − Use the setAttribute() method again and set the download attribute to the download file name value of the hidden element hidden_a.
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 calls the click() method, it starts downloading.
Step 7 - Use the removeChild() method to remove the hidden_a element from the document body.
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>
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.
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]));
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 ofIn 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>
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!