HOWTO · jQuery
How to Download File in jQuery
This tutorial demonstrates how to download a file using jQuery.
On this page
This tutorial will demonstrate how to download a file using jQuery.
jQuery Download File
jQuery can also be used to download a file with the same functionality as JavaScript and HTML. We can use the HTML anchor tag with jQuery to download a file.
Let’s see the step-by-step process:
-
First, create an anchor tag in HTML with the source
#. -
Create a
ready()method so that we can perform the download when the DOM is loaded. -
Inside the
ready()method, create aclickevent that targets the anchor tag. -
Set the error to
preventDefault. -
Finally, set the
hrefof the anchor tag to the file’s path to be downloaded. -
Run the system and click the link. The file will be downloaded.
Let’s try to implement an example based on the above steps:
<!DOCTYPE html>
<html>
<head>
<title>JQuery Downalod File</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<style>
#Main {
border: 5px solid green;
background-color : lightblue;
height: 10%;
width: 20%;
}
</style>
</head>
<body>
<div id = "Main">
<h1>Download File Using jQuery </h1>
<h3>Click the link do download the file..</h3>
<a id="download" href="#"> Download this file</a>
<script>
$(document).ready(function () {
$("#download").click(function (e) {
e.preventDefault();
window.location.href = "delftstack.docx";
});
});
</script>
<div>
</body>
</html>
The code above will download the file on click. See the output:
As we can see, we used window.location.href = "delftstack.docx"; to set the path for the file to download. Here we can also use the attr() to set the attribute href to our path.
See another example:
<!DOCTYPE html>
<html>
<head>
<title>JQuery Downalod File</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<style>
#Main {
border: 5px solid green;
background-color : lightblue;
height: 10%;
width: 20%;
}
</style>
</head>
<body>
<div id = "Main">
<h1>Download File Using jQuery </h1>
<h3>Click the link do download the file..</h3>
<a id="download" href="#"> Download this file</a>
<script>
$(document).ready(function () {
$("#download").click(function (e) {
$("#download").attr({target: '_blank', href : "delftstack.docx"})
});
});
</script>
<div>
</body>
</html>
Now, the code will use the attr method to download the file from the given path. See the output: