file-saver下载文件

496 阅读1分钟
项目中版本
"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();
  });
};