Is it possible to download File Using Javascript/jQuery?

javascript
jquery

(summerbreeze384) #1

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 new window/tab. How is this possible?


(1337_BOT) #2

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'});

(afree) #3

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.


(Yay) #5

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');