How to download File Using JavaScript/jQuery ?

Suppose you want to download a file when you click on a link. For downloading the file, we mentioned here to implementation as well as folder structure where you can see the file location.

Approach:

  • Create an anchor tag link on the normal HTML page. We want to download a file when we click on an anchor tag link(Download this file).

html

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        Download File Using 
        JavaScript/jQuery
    </title>
</head>
  
<body>
    <h1>
        Download File Using 
        JavaScript/jQuery
    </h1>
  
    <a id="link" href="#">
        Download this file
    </a>
</body>
  
</html>

chevron_right


  • Provide with the below JavaScript Code:
$(document).ready(function () {
      $("#link").click(function (e) {
          e.preventDefault();
          window.location.href = "File/randomfile.docx";
      });
});

// Note: url= your file path
  • Note: Replace the above URL with your file path. 
    Implementation and Folder structure is as shown below.

Example:

html

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <script src=
    </script>
</head>
  
<body>
    <h1>
        Download File Using 
        JavaScript/jQuery
    </h1>
      
    <h3>
        For Downloading, Click 
        on the below link.
    </h3>
      
    <a id="link" href="no-script.html">
        Download this file
    </a>
      
    <script>
        $(document).ready(function () {
            $("#link").click(function (e) {
                e.preventDefault();
                  
                window.location.href 
                    = "File/randomfile.docx";
            });
        });
    </script>
</body>
  
</html>

chevron_right


Output:

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.