export async function download(url, params) {
const urls = /api/${url}?${stringify(params)};
const response = await fetch(urls, {
method: 'GET',
headers: {
Authorization: Basic c3dvcmQ6c3dvcmRfc2VjcmV0,
'Blade-Auth': Bearer ${getAccessToken()},
'Content-Type': 'application/x-www-form-urlencoded',
},
});
if (!response.ok) {
throw new Error(HTTP error! status: ${response.status});
}
const blob = await response.blob();
const contentDisposition = response.headers.get('content-disposition');
const filename = decodeURIComponent(contentDisposition).split('=')[1];
const urlBlob = window.URL.createObjectURL(blob);
const a = document.createElement('a');
if (blob) {
a.href = urlBlob;
a.download = filename;
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(urlBlob);
return true;
}
}
以上是相关的说明
download
方法是一个用于下载文件的异步函数,主要功能如下:
构建请求 URL:
- 使用
stringify(params)
将参数转换为查询字符串,并拼接到url
上。- 拼接后的 URL 形如
/api/yourEndpoint?key=value
。发送 GET 请求:
- 通过
fetch
发送请求,携带Authorization
和Blade-Auth
认证头。- 设置
Content-Type
为application/x-www-form-urlencoded
。错误处理:
- 如果
response.ok
为false
,抛出 HTTP 错误。处理响应:
- 将返回的数据转换为
blob
(二进制文件)。- 从
content-disposition
头中提取文件名。创建并触发下载:
- 通过
URL.createObjectURL
生成 Blob URL。- 创建
<a>
标签并设置href
和download
属性,模拟用户点击下载文件。- 下载完成后移除
<a>
标签并释放 Blob URL。返回下载状态:
- 如果文件成功下载,返回
true
。