31

suppose we have a pdf link "http://manuals.info.apple.com/en/iphone_user_guide.pdf"(just for example and to let u know that file is not on my server, i only have the link)...now i have to provide a button on my site that will download the file.

i have tried various things like window.open, href etc. methods but it open the link on other window. i know thats because now all browser comes with a adobe plugin which opens it in another window, but still isnt there any way i give the user the option of download rather than opening it, through client side scripting ..

plz help.. thanks

Alex Naspo
  • 2,052
  • 1
  • 20
  • 37
Dhananjay
  • 734
  • 1
  • 9
  • 14
  • Did you check this one? http://stackoverflow.com/questions/349067/download-a-file-using-javascript – Fopfong Jun 19 '10 at 21:16

7 Answers7

46

Here is a Javascript solution (for folks like me who were looking for an answer to the title):

function SaveToDisk(fileURL, fileName) {
    // for non-IE
    if (!window.ActiveXObject) {
        var save = document.createElement('a');
        save.href = fileURL;
        save.target = '_blank';
        save.download = fileName || 'unknown';

        var evt = new MouseEvent('click', {
            'view': window,
            'bubbles': true,
            'cancelable': false
        });
        save.dispatchEvent(evt);

        (window.URL || window.webkitURL).revokeObjectURL(save.href);
    }

    // for IE < 11
    else if ( !! window.ActiveXObject && document.execCommand)     {
        var _window = window.open(fileURL, '_blank');
        _window.document.close();
        _window.document.execCommand('SaveAs', true, fileName || fileURL)
        _window.close();
    }
}

source: http://muaz-khan.blogspot.fr/2012/10/save-files-on-disk-using-javascript-or.html

Unfortunately this is not working for me with IE11, which is not accepting new MouseEvent. I use the following in that case:

//...
try {
    var evt = new MouseEvent(...);
} catch (e) {
    window.open(fileURL, fileName);
}
//...
lajarre
  • 4,910
  • 6
  • 42
  • 69
  • 1
    error failed no file – Bugfixer Apr 28 '15 at 06:05
  • thanks for the method. it saves the files as "unknown" I changed it to fileURL it saved it as "http---localhost-ielts/gtreading-workbook-Activity_3_1.pdf" Any idea how to fix it? – Johnny Jan 31 '16 at 20:29
  • 2
    @Dino this piece of code should definitely be wiki-ed, enhanced and updated collectively & regularly to account for technology updates. But I have no idea how to achieve this utopic goal on SO :) – lajarre Mar 02 '16 at 17:50
34

Use the HTML5 "download" attribute

<a href="iphone_user_guide.pdf" download="iPhone User's Guide.PDF">click me</a>

2021 Update: Now supported in all major browsers! see: caniuse.com/#search=download

If you need to support older browsers, or you're looking for an actual javascript solution (for some reason) please see lajarre's answer

Kabir Sarin
  • 18,092
  • 10
  • 50
  • 41
  • how does this help in HTML4? Is there another way to do it? – Jacques Aug 15 '14 at 08:57
  • hi, i used a same code but that code is not working in safari could you suggest me any good plugin that is allow to force download pdf file in javascript. – Renish Khunt Feb 23 '15 at 09:55
  • according to caniuse http://caniuse.com/#search=download this is currently not supported in safari. i'm just guessing, but you may be able to use jquery.ajax's `contentType` to achieve this. otherwise if you have control over the server you can tell it to send the file with a binary mime type, of course. – Kabir Sarin Feb 25 '15 at 16:23
  • 1
    This is not answering to the exact question – lajarre Mar 25 '15 at 12:12
  • 2
    The OP doesn't matter to me (with all due respect). This page appears in Google as one of the first results, but is not answering to my query, which is the exact same as the title. Please refer to my answer if you don't get it. – lajarre Mar 25 '15 at 20:42
  • Awesome ! Didn't know about this one and I just love it. – Bogdan Dec 13 '21 at 07:24
7

With JavaScript it is very difficult if not impossible(?). I would suggest using some sort of code-behind language such as PHP, C#, or Java. If you were to use PHP, you could, in the page your button posts to, do something like this:

<?php
header('Content-type: application/pdf');
header('Content-disposition: attachment; filename=filename.pdf');
readfile("http://manuals.info.apple.com/en/iphone_user_guide.pdf");
?>

This also seems to work for JS (from http://www.phpbuilder.com/board/showthread.php?t=10149735):

<body>
<script>
function downloadme(x){
myTempWindow = window.open(x,'','left=10000,screenX=10000');
myTempWindow.document.execCommand('SaveAs','null','download.pdf');
myTempWindow.close();
}
</script>

<a href=javascript:downloadme('http://manuals.info.apple.com/en/iphone_user_guide.pdf');>Download this pdf</a>
</body>
Benny
  • 3,899
  • 8
  • 46
  • 81
5

Here is the perfect example of downloading a file using javaScript.

Usage: download_file(fileURL, fileName);

Sohail Ansari
  • 350
  • 4
  • 10
3

If htaccess is an option this will make all PDF links download instead of opening in browser

<FilesMatch "\.(?i:pdf)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>
jerrygarciuh
  • 21,158
  • 26
  • 82
  • 139
-1

In javascript use the preventDefault() method of the event args parameter.

<a href="no-script.html">Download now!</a>

$('a').click(function(e) {
    e.preventDefault(); // stop the browser from following
    window.location.href = 'downloads/file.pdf';
});
intrepidis
  • 2,870
  • 1
  • 34
  • 36
-2

Using Javascript you can download like this in a simple method

var oReq = new XMLHttpRequest();
// The Endpoint of your server 
var URLToPDF = "https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf";
// Configure XMLHttpRequest
oReq.open("GET", URLToPDF, true);

// Important to use the blob response type
oReq.responseType = "blob";

// When the file request finishes
// Is up to you, the configuration for error events etc.
oReq.onload = function() {
// Once the file is downloaded, open a new window with the PDF
// Remember to allow the POP-UPS in your browser
var file = new Blob([oReq.response], { 
    type: 'application/pdf' 
});

// Generate file download directly in the browser !
saveAs(file, "mypdffilename.pdf");
};

oReq.send();
Nawin
  • 485
  • 8
  • 14