调用API,后台返回了文件对象,没有帮你直接下载的时候,我们一般就把文件处理成blob,然后创建一个a标签使用href进行下载,一般做如下处理即可:
1.使用fetch请求
const downLoadFile = useCallback(async () => {
fetch(url).then(async (res: any) => {
if (res?.status === 200) {
res.blob().then((blob: any) => {
let a: any = document.createElement('a');
let url = window.URL.createObjectURL(blob);
let filename: any = res.headers.get('Content-Disposition');
if (filename) {
filename = filename.split('filename=')[1]; //提取文件名
a.href = url;
a.download = filename; //给下载下来的文件起个名字
a.click();
window.URL.revokeObjectURL(url);
a = null;
}
})
}
})
.catch(error => console.error('Error:', error));
}, [])
2.使用axios请求
axios({
url: api,
method: 'get',
responseType: 'blob'
}).then((res: any) => {
if (res?.status === 200) {
let a: any = document.createElement('a');
let url = window.URL.createObjectURL(new Blob([res.data]));
let filename: any = decodeURI(res.headers['content-disposition']).split('filename=')[1];
if (filename) {
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
a = null;
}
}
})}
axios的方式一般还需要在请求处添加响应类型responseType: blob
3. 设置响应头
有时候遇到需要将权限信息带到响应头中,后台会校验
axios({
url: api,
method: 'get',
responseType: 'blob',
headers: {
"Authorization": `Basic ${Base64.encode(`${values.username}:${values.password}`)}`
}
}).