jQuery Download File from URL and Save

To download a file from a URL and save it using jQuery, you can use the following code:

$.ajax({
url: ‘http://example.com/file.zip’,
method: ‘GET’,
xhrFields: {
responseType: ‘blob’
},
success: function (data) {
var a = document.createElement(‘a’);
var url = window.URL.createObjectURL(data);
a.href = url;
a.download = ‘file.zip’;
document.body.append(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
}
});
[ad_1]

If you want to download any file from URL or server using jQuery; So, Through this tutorial, we will learn how to download any files from URL or server using jQuery.

How to Download File from URL using JQuery

Let’s use the following steps, to implement download file from URL using jQuery:

  • Step 1 – Create HTML
  • Step 2 – Implement jQuery Code
  • Step 3 – Test Code

Step 1 – Create HTML

First of all, create a html file and add the following html code into it:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
  
    <h2>How to Download File using JQuery? - Tutsmake.com</h2>
  
    <a id="d_load" href="#">Click Here!</a>
  
</body>
  

  
</html>

Step 2 – Implement jQuery Code

Then add the following code into html file, which is used to download file from url using jquery:

<script type="text/javascript">
    $(document).ready(function () {
        $("#d_load").click(function (e) {
            e.preventDefault();
            window.location.href = "/documents/test.csv";
        });
    });
</script>

In the above-given line of code:

  • Calling a function after the document is fully ready.
  • Within that function, a constant check is implemented on the element with the id “download”, which is actually an tag and the check is for a “click” event.
  • Then, just use the location.href attribute for the file path.

Step 3 – Test Code

Now, open the above-created HTML file in the browser and click the link to download a file from the given URL.

Conclusion

Through this tutorial, we have learned how to download file from url using jQuery.

Recommended jQuery Tutorials

[ad_2]

Jaspreet Singh Ghuman

Jaspreet Singh Ghuman

Jassweb.com/

Passionate Professional Blogger, Freelancer, WordPress Enthusiast, Digital Marketer, Web Developer, Server Operator, Networking Expert. Empowering online presence with diverse skills.

jassweb logo

Jassweb always keeps its services up-to-date with the latest trends in the market, providing its customers all over the world with high-end and easily extensible internet, intranet, and extranet products.

GSTIN is 03EGRPS4248R1ZD.

Contact
Jassweb, Rai Chak, Punjab, India. 143518
Item added to cart.
0 items - 0.00