JS下載後臺介面返回的二進位制檔案

luncky boy發表於2020-11-30
<div><a class="zhushen2" class="layui-table-link" href="javascript:download(\'' + '' + '\',\'' + d.filePath + '\')"style="margin-top:10px" >下載</a></div>
function download(utl){
  	  var url =utl;
      var that = this;
      //判斷是否IE瀏覽器
      if (!!window.ActiveXObject || "ActiveXObject" in window) {
      		//此處可以載入動畫
            var req = new XMLHttpRequest();
            req.open("post", url, true);
            //監聽進度事件
            req.addEventListener("progress", function (evt) {
                if (evt.loaded > 0 && evt.loaded <= 10000) {
                }
                if (evt.lengthComputable) {
                }
             }, false);
             req.responseType = "blob";
             req.onreadystatechange = function () {
             if (req.readyState === 4 && req.status === 200) {
                 var blob = new Blob([req.response], { type: 'application/force-download' });
                            window.navigator.msSaveBlob(blob, serverFileName);
                        }
             };
             req.send();
        } else {

           var xmlHttp = new XMLHttpRequest(); // XMLHttpRequest 物件用於在後臺與伺服器交換資料
           xmlHttp.open('post', url, true); // 也可以使用POST方式,根據介面
           xmlHttp.responseType = "blob";
           xmlHttp.onprogress = function (e) {
           if (e.loaded >= 0 && e.loaded <= 17800) {

           }
           }
           xmlHttp.onload = function () {
                if (this.status === 200) {
                    var blob = this.response;
                    var reader = new FileReader(); // FileReader() 讀取檔案
                    const blobUrl = window.URL.createObjectURL(blob)
                    reader.readAsDataURL(blob); // readAsDataURL() 用於讀取指定Blob或File的內容
                     reader.onload = function (e) { // onload 檔案讀取成功完成時觸發
                                var fileName = serverFileName;
                                var a = document.createElement('a');
                                a.download = fileName;
                                // e.target.result
                                a.href = blobUrl;
                                $("body").append(a); // 修復firefox中無法觸發click
                                a.click();
                                $(a).remove();
                              
                            }
                        } else {
                          
                        }
                    };
                    xmlHttp.send(); // 把請求傳送到伺服器
                }
}

相關文章