如何使用Content-disposition强制文件下载到硬盘?我想强制浏览器下载pdf文件。我使用以下代码:<a href="../doc/quot.pdf" target=_blank>Click here to Download quotation</a>它使浏览器在新窗口中打开pdf,但我希望它在用户单击时下载到硬盘驱动器。我发现它Content-disposition用于此,但我如何在我的情况下使用它?
2 回答

长风秋雁
TA贡献1757条经验 获得超7个赞
使用最近的浏览器,您也可以使用HTML5下载属性:
<a download="quot.pdf" href="../doc/quot.pdf">Click here to Download quotation</a>
除了MSIE11之外,大多数最近的浏览器都支持它。您可以使用polyfill,类似于此(请注意,这仅适用于数据uri,但这是一个良好的开端):
(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; }})();
- 2 回答
- 0 关注
- 1868 浏览
相关问题推荐
添加回答
举报
0/150
提交
取消