接口返回類型為文件流
1,iframe下載--下面是jquery代碼
//把上一次創建的iframe刪掉,不然隨着下載次數的增多頁面上會一堆的iframe var haveIframe = $("iframe") if(haveIframe){ haveIframe.remove(); } downloadFile(url); function downloadFile(url) { try{ var elemIF = document.createElement("iframe"); elemIF.src = url+'?pSize=1&pNum=1&flag=1&sts=Y'; elemIF.style.display = "none"; document.body.appendChild(elemIF); }catch(e){ zzrw.alert("下載異常!"); } }
2,from表單實現文件流下載
//同樣道理,把上一次創建的form刪掉,不然隨着下載次數的增多頁面上會一堆的form var haveForm = $("#downloadfileform") if(haveForm){ $("#downloadfileform").remove(); } var $eleForm = $("<form id='downloadfileform' method='get'><input id='input_data' name='data' type='hidden'>" + "<input id='pSize' name='pSize' value='"+obj.pSize+"' type='hidden'>"+ "<input id='pNum' name='pNum' value='"+obj.pNum+"' type='hidden'>"+ "<input id='flag' name='flag' value='"+obj.flag+"' type='hidden'>"+ "<input id='sts' name='sts' value='"+obj.sts+"' type='hidden'>"+ "</form>"); $eleForm.attr("action",url); $(document.body).append($eleForm); //提交表單,實現下載 $eleForm.submit();
3,vue axios方式下載文件流,並對接口返回的是出錯的json字符串和文件流進行判斷
step1:攔截器里代碼-可根據需求自行編寫此處

step2:接口配置處,responseType寫為blob

調用接口處,vuex的action層

step3:頁面調用
//導出事件 exportData() { this._shopMonthexport(this.getParams()) .then(res => { const blob = new Blob([res.data], { type: "application/vnd.ms-excel;charset=utf-8" });//這里是excel文件,可根據需求自行更改 var contentDisposition = res.headers["content-disposition"]; var patt = new RegExp("filename=([^;]+\\.[^\\.;]+);*"); var result = patt.exec(contentDisposition); var fileName = result[1]; if ("download" in document.createElement("a")) { // 非IE下載 const elink = document.createElement("a"); var reg = /^["](.*)["]$/g; elink.download = decodeURI(fileName.replace(reg, "$1")); //下載后文件名 elink.style.display = "none"; elink.href = URL.createObjectURL(blob);//創建下載的鏈接 document.body.appendChild(elink); elink.click();//點擊下載 URL.revokeObjectURL(elink.href); //釋放掉blob對象 document.body.removeChild(elink);//下載完成移除元素 } else { // IE10+下載 navigator.msSaveBlob(blob, fileName); } }) .catch(e => { console.log(e); }); },
