如何使用Content-disposition强制文件下载到硬盘?

时间:2012-02-08 14:33:06

标签: html download httpresponse content-disposition

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

我使用以下代码:

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

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

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

2 个答案:

答案 0 :(得分:104)

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

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

请参阅维基百科MIME页面上的content-disposition

答案 1 :(得分:8)

使用最近的浏览器,您也可以使用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;
    }

})();