使用 axios 请求 api 下载导出一个文件时,接口返回值可能会出现两种情况:
1、文件流
2、json 对象
responseType 值的类型
| 值 | 数据类型 |
| '' | DOMString(默认类型) |
| arraybuffer | ArrayBuffer 对象 |
| blob | Blob 对象 |
| document | Documnet 对象 |
| json | JavaScript object, parsed from a JSON string returned by the server |
| text | DOMString |
实例
返回值不同情况的处理方式,举例如下:
1.请求设置为 responseType: ‘arraybuffer’
请求成功时,后端返回文件流,正常导出文件;
请求失败时,后端返回 json 对象,如:{“Status”:“false”,“StatusCode”:“500”,“Result”:“操作失败”},也被转成了 arraybuffer
此时请求成功和失败返回的 http 状态码都是 200
解决方案: 将已转为 arraybuffer 类型的数据转回 Json 对象,然后进行判断
代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | async downloadFile (file) { let res = await this.$axios.post(this.API.order.tradeImpExcle, { responseType: "arraybuffer" }); if (!res) return; try { //如果JSON.parse(enc.decode(new Uint8Array(res.data)))不报错,说明后台返回的是json对象,则弹框提示 //如果JSON.parse(enc.decode(new Uint8Array(res.data)))报错,说明返回的是文件流,进入catch,下载文件 let enc = new TextDecoder('utf-8') res = JSON.parse(enc.decode(new Uint8Array(res.data))) //转化成json对象 if (res.Status == "true") { this.refresh() this.$message.success(res.Msg) } else { this.$message.error(res.Result) } } catch (err) { const content = res.data; const blob = new Blob([content]); let url = window.URL.createObjectURL(blob); let link = document.createElement("a"); link.style.display = "none"; link.href = url; link.setAttribute( "download", res.headers["content-disposition"].split("=")[1] ); document.body.appendChild(link); link.click(); } } |
2.请求设置为 responseType: ‘blob’
解决方案: 将已转为 blob 类型的数据转回 Json 对象,然后进行判断
代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | async downloadFile (file) { let formData = new FormData(); formData.append("allTradesExcelFile", file); let res = await this.$axios.post(this.API.order.tradeImpExcle, formData, { responseType: "blob" }); if (!res) return; let r = new FileReader() let _this = this r.onload = function () { try { // 如果JSON.parse(this.result)不报错,说明this.result是json对象,则弹框提示 // 如果JSON.parse(this.result)报错,说明返回的是文件流,进入catch,下载文件 res = JSON.parse(this.result) if (res.Status == "true") { _this.refresh() _this.$message.success(res.Msg) } else { _this.$message.error(res.Result) } } catch (err) { const content = res.data; const blob = new Blob([content]); let url = window.URL.createObjectURL(blob); let link = document.createElement("a"); link.style.display = "none"; link.href = url; link.setAttribute( "download", res.headers["content-disposition"].split("=")[1] ); document.body.appendChild(link); link.click(); } } r.readAsText(res.data) // FileReader的API } |
转自:https://blog.csdn.net/lhz_333/article/details/102495755