鍍金池/ 問答/HTML/ JS中通過ajax接口后臺返回的文件流如何進(jìn)行下載?求助

JS中通過ajax接口后臺返回的文件流如何進(jìn)行下載?求助

代碼如下

var url = "{#$apiHost#}/aw/export?brand_ids="+brand_ids;
var settings = {
  "async": true,
  "crossDomain": true,
  "url": url,
  "method": "GET",
  "headers": {"token": "{#$smarty.session.pc_token#}","os": "1"}
}
$.ajax(settings).done(function (response) {
    // console.log(response);


});

其中headers是權(quán)限檢查,done中返回的response就是文件流(一個zip壓縮包),請問如何在JS中正常下載這個文件流呢?

回答
編輯回答
吃藕丑

@改名字很傷神

我查資料有個這種方法,

var url = "{#$apiHost#}/aw/export?brand_ids="+brand_ids;
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.withCredentials = true;
xhr.responseType = "blob";
xhr.setRequestHeader("token", "{#$smarty.session.pc_token#}");
xhr.setRequestHeader("os", "1");
xhr.send();
xhr.onload = function() {
    if (this.status == 200) {
        try{
            var elemIF = document.createElement("iframe");
            elemIF.src = this.responseURL;
            elemIF.style.display = "none";
            document.body.appendChild(elemIF);
        }catch(e){
        }
    }
}

但是用這種方法有如下這個問題,不知如何解決
圖片描述

2018年8月8日 00:52
編輯回答
只愛你

Blobxhr 2的內(nèi)容,jquery不支持,可以考慮axios或原生xhr/fetch

2018年2月13日 15:13
編輯回答
玄鳥

返回這個文件的地址,然后直接跳到那里去,會不會方便一點?

2018年3月28日 13:41