前端接收二进制文件流,并通过浏览器下载文件
As known,用blob来接收并解析二进制流。
new Blob的时候入参两个,第一个是二进制字符串的数组,专业来说是一个由 ArrayBuffer,ArrayBufferView,Blob,DOMString 等对象构成的数组,第二个是可选对象,包含type(默认为“”,代表数组的MIME类型)和endings(不常用)。其中type应和后端返回接口的content-type一致(type: “application/json”)
在请求接口的时候需要使用原生axios, 才能正确设置responseType为blob,不然是无法解析的
axios({
url:``,
data: {addServiceType: this.serviceType},
headers:{
Authorization: window.localStorage.getItem('Authorization')
},
responseType: 'blob',
method:'post'
})
.then((res) => {
let b = new Blob([res.data], { type: "application/json" });
let url = window.URL.createObjectURL(b); //生成文件流下载链接
let a = document.createElement('a')
a.download = 'sheet.xls'
a.href = url
a.click()
})
```