开发中遇到了所以记录一下。。。。
不废话,我直接直接上代码吧
这里还解决了后端传的json格式,前端下载不了json的文件问题
1、定义一个方法downLoadFUnOne
downLoadFUnOne(data, fileName) { var reader = new FileReader(); var bData = data; reader.readAsText(bData, "utf-8"); reader.onload = function(e) { try { var msg = JSON.parse(reader.result); if (msg && msg.resultCode == "401") { clearLoginInfo(); console.log("401-->token"); window.location.href = window.SITE_CONFIG.nspmGxb; } if(bData.type == 'application/json'){ // 将对象转为json字符串 const jsonStr = JSON.stringify(msg) // 创建一个文本文件Blob对象 const blob = new Blob([jsonStr], { type: 'application/json' }) // 构造下载链接 const url = URL.createObjectURL(blob) // 创建下载链接的a标签 const a = document.createElement('a') a.href = url a.download = fileName // 模拟点击下载链接 document.body.appendChild(a) a.click() document.body.removeChild(a) // 释放Blob占用的资源 URL.revokeObjectURL(url) } } catch (err) { let content = data; if (window.navigator.msSaveBlob) { window.navigator.msSaveBlob(content, fileName); } else { let elink = document.createElement("a"); elink.download = fileName; elink.style.display = "none"; let blob = new Blob([content], { type: "application/octet-stream" }); elink.href = URL.createObjectURL(blob); document.body.appendChild(elink); elink.click(); document.body.removeChild(elink); } } }; },
2、点击下载在调用上面的downLoadFUnOne方法
downLoadFun(row,index) { this.activeIndex = index this.$http({ url: this.$http.adornUrl( `server-mgr/assetExport/downloadAssetFile/${row.id}` ), method: "get", responseType: "blob" // data: this.$http.adornData(this.dataForm), }).then(({ data }) => { if(this.activeIndex == index){ this.downloadIcon = true setTimeout(()=>{ this.downloadIcon = false },3000) } this.downLoadFUnOne(data, row.fileName); // const contentDisposition = data.headers['content-disposition']; // const fileName = decodeURIComponent(contentDisposition.substring(contentDisposition.indexOf('=') + 1)); // this.downLoadFUnOne(data.data,fileName) }); },