js中如何使用ajax的get来向后台获取文件流进行文件另存为的下载其中header需要传token和os参数到后台进行验证请问这个JS应该如何写?希望大神不吝赐教,谢谢~如下方法后台无法获取header参数,360浏览器中也没有启动另存为的窗口var url = "{#$apiHost#}/aw/export?brand_ids="+brand_ids;var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = "blob";
xhr.setRequestHeader("token", "5f963175cc75613398e25ce2e5da56d7");
xhr.setRequestHeader("os", "1");
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){
}
}
}
xhr.send();
2 回答
慕的地6264312
TA贡献1817条经验 获得超6个赞
改成这样就好了。
var xhh = new XMLHttpRequest(); xhh.open("post", Action.FILES_W_DOWNLOADFILE + "/"+ fileName ); xhh.setRequestHeader("Authorization", this.Axios.defaults.headers.Authorization = JSON.parse(getCookie('userInfo')).tokenType+ ' ' + JSON.parse(getCookie('userInfo')).accessToken); xhh.setRequestHeader("Content-Type","application/json"); xhh.responseType = 'blob'; xhh.onreadystatechange = function () { if (xhh.readyState === 4 && xhh.status === 200) { var name = xhh.getResponseHeader("ajax-filename"); var mimeType = xhh.getResponseHeader("ajax-mimeType"); var blob = new Blob([xhh.response], {type: mimeType}); var csvUrl = URL.createObjectURL(blob); var link = document.createElement('a'); document.body.appendChild(link); //创建的标签添加到body,解决Firefox下无法打开页面的问题 link.href = csvUrl; link.target = '_blank'; link.id = 'linkId', link.className = 'linkId', link.download = decodeURI(name); document.getElementById("linkId").click(); // link.remove(); //将a标签移除 $('.linkId').remove() } }; xhh.send();
添加回答
举报
0/150
提交
取消