If you want to download any file from URL or server using jQuery; So, Through this tutorial, we will learn how to download any file like pdf, txt, CSV, excel, etc, from URL or server using jQuery.
How to Download & Save File from URL using JQuery
Let’s use the following steps to implement the download and save file like pdf, txt, csv, excel, etc 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.