Download File Using Javascript/jQuery


I have a very similar requirement specified here.

I need to have the user's browser start a download manually when $('a#someID').click();

But I cannot use the 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?

5/23/2017 12:26:42 PM

Accepted Answer

Use an invisible <iframe>:

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

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.

12/2/2015 9:38:15 PM

function downloadURI(uri, name) 
    var link = document.createElement("a");
    // If you don't know the name or want to use
    // the webserver default set name = ''
    link.setAttribute('download', name);
    link.href = uri;

Check if your target browser(s) will run the above snippet smoothly:


I'm surprised not a lot of people know about the download attribute for a elements. Please help spread the word about it! You can have a hidden html link, and fake a click on it. If the html link has the download attribute it downloads the file, not views it, no matter what. Here's the code. It will download a cat picture if it can find it.

<a href="" download id="download" hidden></a>

Note: This is not supported on all browsers:


I recommend using the download attribute for download instead of jQuery:

<a href="your_link" download> file_name </a>

This will download your file, without opening it.


If you are already using jQuery, you could take adventage of it to produce a smaller snippet
A jQuery version of Andrew's answer:

var $idown;  // Keep it outside of the function, so it's initialized once.
downloadURL : function(url) {
  if ($idown) {
  } else {
    $idown = $('<iframe>', { id:'idown', src:url }).hide().appendTo('body');
//... How to use it:

Works on Chrome, Firefox and IE8 and above.

var link=document.createElement('a');
link.href=url ;;