How to Trigger a File Download when Clicking an HTML Button or JavaScript?
Last Updated :
20 Sep, 2024
Triggering file downloads in JavaScript refers to initiating the download of files directly from a webpage when a user clicks a button or link. This can be achieved using HTML5's download attribute or custom JavaScript functions, allowing dynamic and user-friendly file-downloading experiences.
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
- The download attribute on the <a> tag prompts a download when the link is clicked.
- download="GFG" specifies the default filename for the downloaded file.
- Button: The button inside the <a> tag triggers the download when clicked.
html
<!DOCTYPE html>
<html>
<head>
<title>Using Download attribute </title>
<style>
p {
color: green;
}
</style>
</head>
<body>
<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:
Using Download attribute Example OutputUsing 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>
Using a custom javascript functionÂ
</title>
<style>
p {
color: green;
}
</style>
</head>
<body>
<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
let 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 () {
let text =
document.getElementById("text").value;
let filename = "GFG.txt";
download(filename, text);
}, false);
</script>
</body>
</html>
Output:
Using a custom javascript function 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>
<html>
<head>
<title>Download Images using Axios</title>
<style>
.scroll {
height: 1000px;
background-color: white;
}
</style>
</head>
<body>
<h1 style="color: green">GeeksforGeeks</h1>
<button onclick="downloadImage()">
Download Image
</button>
<p class="scroll">
By clicking the download button,
a random image will be generated.
</p>
<script src=
"https://cdnjs.cloudflare.com/ajax/libs/axios/0.19.2/axios.min.js">
</script>
<script>
function downloadImage() {
axios({
url: 'https://picsum.photos/500/500',
method: 'GET',
responseType: 'blob'
})
.then((response) => {
if (response.status === 200) {
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();
document.body.removeChild(link);
window.URL.revokeObjectURL(url);
} else {
console.error('Error: Received non-200 status code');
}
})
.catch((error) => {
console.error('Error downloading the image:', error);
});
}
</script>
</body>
</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.
Similar Reads
How to Download PDF File on Button Click using JavaScript ? Sometimes, a web page may contain PDF files that can be downloaded by the users for further use. Allowing users to download the PDF files can be accomplished using JavaScript. The below methods can be used to accomplish this task. Table of Content Using html2pdf.js libraryUsing pdfmake LibraryUsing
5 min read
Create A Download Button with Timer in HTML CSS and JavaScript In this article, we will discuss how to create a Download button with a timer attached to it using HTML, CSS, and Javascript.Our goal is to create a button that has a timer attached to it. The download should only start after the timer has run out, which we will achieve using the setTimeout and setI
2 min read
How to Download Image on Button Click in JavaScript? Downloading an image on a button click in JavaScript involves creating a mechanism to trigger the download action when a user clicks a button. Below are the approaches to download image on button click in JavaScript: Table of Content Using Anchor Tag with Download AttributeUsing Fetch APIUsing Ancho
3 min read
How to detect when cancel is clicked on file input using JavaScript ? This article describes the method to handle a situation when the user tries to input a file and later fails to upload the file. It gives the status to the user that the file is not uploaded. This may be useful in situations when an important file needs to be submitted or the application requires the
3 min read
How to download File Using JavaScript/jQuery ? The ability to download files directly from a website is an essential feature for many web applications. Whether you're providing documents, images, or other data, enabling users to download files seamlessly enhances their experience and ensures they can access the content offline. This article prov
2 min read
Sound Generation on Clicking the Button using JavaScript The sound generation after clicking the button, receiving notifications, or at the time of page load can be done by using JavaScript. Note:URL provided in the playSound function can be changed to give the custom sound url. Style property is not the part of implementation. It is used to provide a nic
1 min read