Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force download a pdf link using javascript/ajax/jquery

Tags:

javascript

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

like image 440
Dhananjay Avatar asked Jun 19 '10 21:06

Dhananjay


2 Answers

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); } //... 
like image 188
lajarre Avatar answered Sep 21 '22 09:09

lajarre


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

like image 35
Kabir Sarin Avatar answered Sep 19 '22 09:09

Kabir Sarin