Stopbyte

Is it possible to download File Using Javascript/jQuery?

I need to start download manually when $('a#someID').click();

But I cannot use window.href method, since it replaces the current page contents with the file you’re trying to download.

Instead, I want to open the download in a new window/tab. How is this possible?

1 Like

Use an invisible Iframe. If the file type is not nonsensical then set it up to make it as such.

$('a#someID').attr({target: '_blank', 
                    href  : 'http://myhost/directorypath/yourdownloadedfile.exe'});
2 Likes

Use an invisible <iframe>:

<iframe id="my_iframe" style="display:none;">
<script>
function Download(url) {
    document.getElementById('my_iframe').src = url;
};
</script>

To force the browser to download a file it would otherwise be capable of rendering (such as HTML or text files), you need the server to set the file’s MIME Type to a nonsensical value, such as application/x-please-download-me or alternatively application/octet-stream, which is used for arbitrary binary data.

If you only want to open it in a new tab, the only way to do this is for the user to a click on a link with its target attribute set to _blank.

In jQuery:

$('a#someID').attr({target: '_blank', 
                    href  : 'http://localhost/directory/file.pdf'});

Whenever that link is clicked, it will download the file in a new tab/window.

If you are using jQuery, you could take advantage of it to produce a smaller snippet
Something like this will give similar results as @afree 's snippet:

var $idown;  // Keep it outside of the function, so it's initialized once.
downloadURL : function(url) {
  if ($idown) {
    $idown.attr('src',url);
  } else {
    $idown = $('<iframe>', { id:'idown', src:url }).hide().appendTo('body');
  }
},
  • How to use it
    something like this should be all you need to use:
    downloadURL('http://whatever.com/file.pdf');
1 Like

Another method that is not shown above, in my case using Vanilla Javascript only:

function download(filename, text) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}

// Start file download.
download("hello.txt","This is the content of my file");

The download attribute works only where href is set, as for with the a tag or the area tag.
It indicates that the target will be downloaded when a user clicks on the hyperlink. This attribute needs href to be set in order to work.

# html
<input type="button" id="dwn-btn" value="Download file"/>

At a click, a text file Download needs to be initiated.
So, we need to call the function Download when the button above is clicked!

Here is how to do it:

     document.getElementById("dwn-btn").addEventListener("click", function(){
         // Generate download of hello.txt file with SomeText
        var text = SomeText
        var filename = "hello.txt";
        
        download(filename, text);
    }, false);
1 Like

Downloading an image using Javascript.

This method works only when you want to download an image file… and it does not need the use of JQuery.

You can load the image into a canvas element get the data URL of the canvas and open a new window with the data URL as the source.

  // Get a reference to the image element
     var image = document.getElementById("img");
 
     // Take action when the image has loaded
     image.addEventListener("load", function () {
     var imgCanvas = document.createElement("canvas"),
             imgContext = imgCanvas.getContext("2d");
 
         // Make sure canvas is as big as the picture
         imgCanvas.width = image.width;
         imgCanvas.height = image.height;
 
         // Draw image into canvas element
         imgContext.drawImage(image, 0, 0, image.width, image.height);
 
           // Get canvas contents as a data URL
             var imgAsDataURL = imgCanvas.toDataURL("image/png");
     
             // Save image into localStorage
             try {
                 localStorage.setItem("my image", imgAsDataURL);
             }

        // catch errors
         catch (e) {
             console.log("Storage failed: " + e);
         }
     }, false); 

Note:

  • This only works if the JS is running on the same site as the image, otherwise, you’ll get a CORS security error. And to fix it try defining crossOrigin attr with anonymous in image.

  • You can read more about this issue here: Allowing cross-origin use of images and canvas.

2 Likes

Yes, you can download files using JavaScript or jQuery. You hardly can create a link element with the file URL and trigger a click event to initiate the download. Instead of this you can use the fetch API to fetch the file and then save it locally. Both methods are commonly used depending on your specific needs and browser compatibility.