网站首页 » » 前端下载非预览解析

前端下载非预览解析

August 11, 2021

如果同域超链接可以实现下载文件,但是跨域,只能在线预览。

// url 下载 非预览
getBlob (url: string) {
  return new Promise(resolve => {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.responseType = 'blob';
    xhr.onload = () => {
      if (xhr.status === 200) {
        resolve(xhr.response);
      }
    };

    xhr.send();
  });
}
saveAs (blob: any, filename: string | undefined){  
  const link: any = document.createElement('a');
  const body: any = document.querySelector('body');
  link.href = window.URL.createObjectURL(blob);
  link.download = filename;
  // fix Firefox
  link.style.display = 'none';
  body.appendChild(link);
  link.click();
  body.removeChild(link);
  window.URL.revokeObjectURL(link.href);
}

downloadUrl (url: string, name: string){
  let filename= name;
    FormUtils.getBlob(url).then(blob => {
      FormUtils.saveAs(blob, filename);
    });
}