재우니의 블로그

 

AJAX 및 jQuery를 사용하여 파일을 BLOB로 다운로드 하기

 

 

AJAX 및 jQuery를 사용하여 파일을 BLOB로 다운로드하는 방법을 설명합니다. PDF 파일은 jQuery AJAX 및 XmlHttpRequest(XHR) 요청을 사용하여 BLOB로 다운로드된 다음 jQuery를 사용하여 브라우저에서 다운로드하도록 전송됩니다.

 

PDF 파일은 디렉토리 내의 Files라는 폴더에 저장됩니다.

DownloadFile JavaScript 함수 내에서 파일의 URL은 jQuery AJAX 함수에 매개변수로 전달됩니다.

 

jQuery AJAX 함수 내에서 XmlHttpRequest(XHR) 호출을 사용하여 PDF 파일이 바이트 배열(이진 데이터)로 다운로드됩니다.
마지막으로 받은 Byte Array(Binary Data)를 BLOB 객체로 변환하고 File을 Browser에 다운로드합니다.

 

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
</head>
<body>
    <input type="button" value="Download PDF File" onclick="DownloadFile('Sample.pdf')" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
    <script type="text/javascript">
        function DownloadFile(fileName) {
            //Set the File URL.
            var url = "Files/" + fileName;
 
            $.ajax({
                url: url,
                cache: false,
                xhr: function () {
                    var xhr = new XMLHttpRequest();
                    xhr.onreadystatechange = function () {
                        if (xhr.readyState == 2) {
                            if (xhr.status == 200) {
                                xhr.responseType = "blob";
                            } else {
                                xhr.responseType = "text";
                            }
                        }
                    };
                    return xhr;
                },
                success: function (data) {
                    //Convert the Byte Data to BLOB object.
                    var blob = new Blob([data], { type: "application/octetstream" });
 
                    //Check the Browser type and download the File.
                    var isIE = false || !!document.documentMode;
                    if (isIE) {
                        window.navigator.msSaveBlob(blob, fileName);
                    } else {
                        var url = window.URL || window.webkitURL;
                        link = url.createObjectURL(blob);
                        var a = $("<a />");
                        a.attr("download", fileName);
                        a.attr("href", link);
                        $("body").append(a);
                        a[0].click();
                        $("body").remove(a);
                    }
                }
            });
        };
    </script>
</body>
</html>

 

Download_PDF_Button_Click_jQuery.zip
0.08MB

 

 

 

https://www.aspsnippets.com/Articles/Download-File-as-BLOB-using-AJAX-and-jQuery.aspx

 

Download File as BLOB using AJAX and jQuery

Here Mudassar Khan has explained with an example, how to download file as BLOB using AJAX and jQuery. The PDF file will be downloaded as BLOB using jQuery AJAX and XmlHttpRequest (XHR) request and then will be sent for download in the Browser using jQuery.

www.aspsnippets.com