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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9195304/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 22:22:38  来源:igfitidea点击:

How to Use Content-disposition for force a file to download to the hard drive?

htmldownloadhttpresponsecontent-disposition

提问by Krish

I want to force the browser to download a pdffile.

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

I am using the following code :

我正在使用以下代码:

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

It makes the browser open the pdf in a new window, but I want it to download to the hard drive when a user clicks it.

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

I found that Content-dispositionis used for this, but how do I use it in my case?

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

回答by Oded

On the HTTP Response where you are returning the PDF file, ensure the content disposition header looks like:

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

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

See content-dispositionon the wikipedia MIME page.

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

回答by inf3rno

With recent browsers you can use the HTML5 download attribute as well:

对于最近的浏览器,您也可以使用 HTML5 下载属性:

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

It is supported by most of the recent browsers except MSIE11. You can use a polyfill, something like this (note that this is for data uri only, but is is a good start):

除了 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;
    }

})();