前端项目下载文件也是一个比较高频的功能,然而不是所有的下载都可以通过a标签下载,比方说图片,它直接去预览了,就很麻烦;给用户造成了困扰;
项目中版本
"file-saver": "^2.0.5",
import SaveAS from 'file-saver';
export function HandleUrlDownloadFile(filename: string, url: string){
return new Promise((resolve, reject) => {
UrlToBlob(url).then((blob: any) => {
SaveAS(blob, filename || '下载文件');
resolve(filename);
}).catch(() => {
reject();
});
})
}
// url转blob
export function UrlToBlob(url: string) {
return new Promise((resolve, reject) => {
const xhr: any = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.setRequestHeader('Authorization', 'Basic a2VybWl0Omtlcm1pdA==');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
resolve(xhr.response);
} else {
// 错误处理
reject(xhr.statusText);
};
};
};
xhr.send();
});
};