接口返回类型为文件流
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); }); },