使用原生请求下载后端返回的二进制流可以解决空白问题,直接看代码:
// 下载函数
export async function downloadFn(response: any, filename: string) {
//2.创建FileReader对象,用于读取文件
const reader = new FileReader();
//3.将文件读取为文本
reader.readAsText(response, 'utf-8');
//4.处理读取事件
//4.1读取完成事件,获取数据
reader.onload = (e: any) => {
console.log(e, 123456);
// 给予提示,返回为json
if (e.currentTarget.result.indexOf('"code":"0"') !== -1) {
const handledRes = JSON.parse(e.currentTarget.result);
message.error(handledRes?.msg);
} else {
// 成功,返回的是文件流
const url = window.URL.createObjectURL(response);
const link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.setAttribute('download', filename);
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
};
}
// 用这种原生请求下载后端返回的二进制流打开就不会出现空白
export async function downloadFileStreamFun(reqUrl: string, filename: string) {
return new Promise(function (resolve, reject) {
const xhr = new XMLHttpRequest();
xhr.open('get', reqUrl, true);
xhr.responseType = 'blob';
xhr.onload = function () {
console.log(xhr, '打印构造函数xhr');
//即使是404也会进入这个相应函数,所以需要检测状态
if (xhr.status == 200) {
//完成许诺,返回响应文本
resolve(xhr.response);
downloadFn(xhr.response, filename);
} else {
//完成未完成,返回错误
reject(Error(xhr.statusText));
}
};
xhr.send();
});
}
5634

被折叠的 条评论
为什么被折叠?



