我想强制浏览器下载pdf
文件。
我正在使用以下代码:
<a href="../doc/quot.pdf" target=_blank>Click here to Download quotation</a>
它使浏览器在新窗口中打开pdf,但是我希望在用户单击它时将其下载到硬盘。
我发现它Content-disposition
用于此目的,但是在我的情况下该如何使用?
Answers:
在要返回PDF文件的HTTP响应上,确保内容处置标头如下所示:
Content-Disposition: attachment; filename=quot.pdf;
请参阅Wikipedia MIME页面上的内容配置。
在最近的浏览器中,您还可以使用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;
}
})();