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
Non-linear Components In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
Spring Boot Tutorial Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Class Diagram | Unified Modeling Language (UML) A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
Backpropagation in Neural Network Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
3-Phase Inverter An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read