0

I want to trigger a file download using javascript only

I know how to do it with html, but i need to trigger the download specifically with javascript, on a button click.

The reason i am not doing it with html is because i want to use a variable as file name later on.

i have used this

$("#button").click(function(){
    window.location = 'files/aaa.pdf';
});

but it only opens the pdf on the same window instead of prompting the user to download it.

I have also tried using this:

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

But it fails to produce results.

G90DD
  • 29
  • 1
  • 1
  • 5
  • I think this is what you want [Download File Using Javascript/jQuery]. [Download File Using Javascript/jQuery]:http://stackoverflow.com/questions/3749231/download-file-using-javascript-jquery – Samvel Petrosov May 22 '16 at 20:12
  • I am a bit confused by this, where am i suppsoed to put the path to the file( files/aaa.pdf)? At the url part? it breaks my code – G90DD May 22 '16 at 20:16
  • Perhaps this answer http://stackoverflow.com/a/28946907/4358405 based on `download=true` attribute would help doing that entirely in JS, without server side changes. I haven't tried that technique though. – TMG May 22 '16 at 21:09
  • It's not fully sopported yet http://caniuse.com/#search=download%20attribute – Denys Medvediev Jul 26 '17 at 14:39

1 Answers1

-1

You should set the MIME type of PDF to application/octet-stream in your web server. This will make the browser download the PDF instead of displaying it.

kagelos
  • 423
  • 8
  • 19
  • I think the missing HTTP header is rather `Content-Disposition: attachment; filename="" ` How to set it depends on the web server that OP is using – TMG May 22 '16 at 21:06