87

我想强制浏览器下载pdf文件。

我正在使用以下代码:

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

它使浏览器在新窗口中打开 pdf,但我希望它在用户单击它时下载到硬盘驱动器。

我发现它Content-disposition用于此,但在我的情况下如何使用它?

4

2 回答 2

134

在返回 PDF 文件的 HTTP 响应中,确保内容处置标头如下所示:

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

请参阅维基百科 MIME 页面上的内容处置。

于 2012-02-08T14:37:16.673 回答
15

对于最近的浏览器,您也可以使用 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;
    }
    
})();
于 2017-03-14T16:10:28.213 回答