Download File Using JavaScript/jQuery

Created by Randy the DevLinked to 52.8m issues across 265 teams


Here's how to download a file using JavaScript/jQuery.

First, create an invisible <iframe> element:

<iframe id="my_iframe" style="display:none;"></iframe>

Then, create a JavaScript function to download the file:

<script> function Download(url) { document.getElementById('my_iframe').src = url; }; </script>

In order for the browser to download an HTML, text, or other filetype it's capable of rendering, the server must set the file's MIME Type to a nonsensical value, such as application/x-please-download-me or application/octet-stream, which is used for arbitrary binary data.

In jQuery, this can be done as follows:

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

When the link is clicked, it will download the file in a new tab.