How to use Content-disposition to force download a file to your hard drive?

I want to force the browser to download the pdf file.

I am using the following code:

 <a href="../doc/quot.pdf" target=_blank>Click here to Download quotation</a> 

This makes the browser open pdf in a new window, but I want it to load onto the hard drive when the user clicks on it.

I found that Content-disposition used for this, but how to use it in my case?

+46
html download content-disposition
Feb 08 2018-12-12T00:
source share
2 answers

In the HTTP response in which you are returning the PDF file, make sure the content placement header looks like this:

 Content-Disposition: attachment; filename=quot.pdf; 

See content-disposition on the MIME wikipedia page.

+79
Feb 08 2018-12-12T00:
source share

In recent browsers, you can also use the HTML5 download attribute:

 <a download="quot.pdf" href="../doc/quot.pdf">Click here to Download quotation</a> 

Supported by most recent browsers except MSIE11. You can use polyfill, something like this (note that this is only for uri data, but this is a good start):

 (function (){ addEvent(window, "load", function (){ if (isInternetExplorer()) polyfillDataUriDownload(); }); function polyfillDataUriDownload(){ var links = document.querySelectorAll('a[download], area[download]'); for (var index = 0, length = links.length; index<length; ++index) { (function (link){ var dataUri = link.getAttribute("href"); var fileName = link.getAttribute("download"); if (dataUri.slice(0,5) != "data:") throw new Error("The XHR part is not implemented here."); addEvent(link, "click", function (event){ cancelEvent(event); try { var dataBlob = dataUriToBlob(dataUri); forceBlobDownload(dataBlob, fileName); } catch (e) { alert(e) } }); })(links[index]); } } function forceBlobDownload(dataBlob, fileName){ window.navigator.msSaveBlob(dataBlob, fileName); } function dataUriToBlob(dataUri) { if (!(/base64/).test(dataUri)) throw new Error("Supports only base64 encoding."); var parts = dataUri.split(/[:;,]/), type = parts[1], binData = atob(parts.pop()), mx = binData.length, uiArr = new Uint8Array(mx); for(var i = 0; i<mx; ++i) uiArr[i] = binData.charCodeAt(i); return new Blob([uiArr], {type: type}); } function addEvent(subject, type, listener){ if (window.addEventListener) subject.addEventListener(type, listener, false); else if (window.attachEvent) subject.attachEvent("on" + type, listener); } function cancelEvent(event){ if (event.preventDefault) event.preventDefault(); else event.returnValue = false; } function isInternetExplorer(){ return /*@cc_on!@*/false || !!document.documentMode; } })(); 
+3
Mar 14 '17 at 16:10
source share



All Articles