我想强制浏览器下载一个pdf
文件。
我正在使用以下代码:
<a href="../doc/quot.pdf" target=_blank>Click here to Download quotation</a>
它使浏览器在一个新窗口中打开pdf,但我希望它在用户点击时下载到硬盘上。
我发现Content-disposition
用于此,但在我的情况下如何使用它?
在返回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;
}
})();