What is the equivalent of wget in javascript to download a file from a given url?

14,141

Solution 1

After a exploring more than a month, with a help of my friend, we were able to find out the following.

The website where the file is hosted is not allowing us to download the file using window.location = url; or window.open(url);

Finally we had to use the data-downloadurl support from HTML5 as follows

<a href="<url-goes-here>" data-downloadurl="audio/mpeg:<filename-goes-here>:<url-goes-here>" download="<filename-goes-here>">Click here to download the file</a>

We embed this html into the host html and when clicked on the link, it triggers the download.

Solution 2

Why not use:

 function download_file() {
   var url = "http://www.example.com/file.doc"
   window.location = url;
 }

See https://developer.mozilla.org/en/DOM/window.location

If you need to open this in a new window/tab first then use:

 function download_file() {
   var url = "http://www.example.com/file.doc"
   window.open(url);
 }

See https://developer.mozilla.org/en/DOM/window.open

Share:
14,141
Sangeeth Saravanaraj
Author by

Sangeeth Saravanaraj

An enthusiastic programmer!

Updated on June 05, 2022

Comments

  • Sangeeth Saravanaraj
    Sangeeth Saravanaraj almost 2 years

    "wget http://www.example.com/file.doc" downloads that file to the local disk.

    What is the equivalent of the above in javascript? for example, consider the following html snippet.

    <html>
    <head>
       <script language="JavaScript">
          function download_file() {
             var url = "http://www.example.com/file.doc"
             //
             // Question: 
             //
             // what should be done here to download 
             // the file in the url?
             //
          }
       </script>
    </head>
    <body>
       <input type="button" value="Download" onclick="download_file()">
    </body>
    </html>
    

    Please suggest a solution that is compliant with all the browsers.

    Sangeeth.