How to download file using JQuery?

In this article we will learn how to download file using jquery. This post give easy example of jquery download file from url. To download files using JQuery, you can achieve it by triggering a file download in multiple methods. 

This article provides a comprehensive guide on how to implement file downloads using JQuery. Complete with a detailed folder structure to help you locate and manage your file directory.

Approach:

Create an anchor tag link on the HTML page. We want to download a file when we click on an anchor tag link. You can consider below example.

I will give you a very easy example of how to download file in jquery. We will use window.location.href to download response. So, let’s run the below html file.

Example: How to download file using JQuery
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>

<body>
    <h1>How to download file using JQuery? - webstuffsolution.com</h1>
    
    <a id="downloadFile" href="#">Click to Download</a>

</body>

</html>
Javascript code
<script>
    $(document).ready(function(){
        $("#downloadFile").click(function(e) {
           e.preventDefault();
           window.location.href = url;
        });
    });
    // Note: url = Your file path
</script>

Here:

  • href = url is the path to the file you want to download.
  • You trigger a click on the hidden <a> tag using JQuery when the button is clicked.  
Download a file via Blob

If the content is dynamically generated or comes from an API, you can use the Blob object to trigger download.

Example
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>

<body>
    <h1>How to download file using JQuery? - webstuffsolution.com</h1>
    
    <a id="downloadFileBlob" href="#">Click to Download</a>

</body>

</html>
Javascript code
$('#downloadFileBlob').on('click', function(){
    var data = new Blob(["This is the content of the file."], {type: 'text/plain'});
    var url = window.URL.createObjectURL(data);
    var a = $('<a />', {
        href: url,
        download: 'example.txt'
    }).appendTo('body').get(0).click();
    window.URL.revokeObjectURL(url);
});

Here, 

  • Blob object is created with text content(“This is the content of the file.”)
  • The file will be downloaded as example.txt when the button is clicked.

These are common methods to download files using JQuery depending on your needs and the data source.

I hope this tutorial help you.

Leave a Reply

Your email address will not be published. Required fields are marked *