Programing

Content-disposition을 사용하여 파일을 하드 드라이브에 강제로 다운로드하는 방법은 무엇입니까?

crosscheck 2020. 11. 5. 07:43
반응형

Content-disposition을 사용하여 파일을 하드 드라이브에 강제로 다운로드하는 방법은 무엇입니까?


브라우저에서 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;

참조 내용 - 처리 위키 피 디아 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;
    }

})();

참고URL : https://stackoverflow.com/questions/9195304/how-to-use-content-disposition-for-force-a-file-to-download-to-the-hard-drive

반응형