基础导出功能的实现
.then(res=>{
const {
url } = res // 从请求中得到文件的路径
const a = document.createElement('a');
a.href = url;
const fileName = "test";
a.download = decodeURIComponent(fileName);
a.click();
})
返回Blob二进制文件对象的 导出功能实现
如果后台返回的不是路径
而是blob对象 就是如下图
导出的实现代码
.then(res =>
res.blob().then(blob => {
const url=window.URL.createObjectURL(blob)
const a = document.createElement('a');
a.href = url;
const fileName = "test";
a.download = decodeURIComponent(fileName);
a.click();
})
)
返回ArrayBuffer二进制文件对象的 导出功能实现
后面使用了EggJs作为中间层,可能是因为没有设置头部参数,后台返回的是ArrayBuffer二进制文件对象,如下图
思路:转换成Blob格式,再进行下载
导出的实现代码:
// 文件流处理
const respStreamHandle = async (response, options = {
}) => {
const respStr = await response.text();
const data = isJSON(respStr) ? JSON.parse(respStr) : respStr;
if (data.data) {
var blob = new Blob([new Uint8Array(data.data.data)], {
type: "application/zip"
})
let url = window.URL.createObjectURL(blob)
const a = document.createElement('a');
a.href = url;
const fileName = "test";
a.download = decodeURIComponent(fileName);
a.click();
}
// return responseData;
};
return fetch(url.indexOf('http') !== -1 ? url : `${
API_URL_PREFIX}${
url}`, newOptions)
.then(checkStatus)
.then(response => respStreamHandle(response))
.catch(e => {
console.log('------模版下载失败------', e);
});
一直以为是在bff层做修改,所以琢磨了很久,但是后来发现在项目的接收处进行转化就可以
想了解 ArrayBuffer 与 Blob 的区别及互转的代码