文件流下载公用

请求加入responseType = "blob";
 
——————————————————————————————————————
 
                

api.then(res =>{
 //用来读取文件blob返回type为application/json的错误信息

  if (res.response.type === 'application/json') {

    const reader = new FileReader()

     reader.onload = (event) => {

       const errorMsg = JSON.parse(event.target.result);

      //alert()

     }

     reader.readAsText(res.response)
     return;
   }
  const name= 'aa.txt';
  const blobs = res.response
   globalDownload(blobs, name);
})
 
function globalDownload(blob,filename){
  download(blob, filename);
};
 
function download(filename) {
 const blob = new Blob([res]);
  if (window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveOrOpenBlob(blob, filename);
  } else {
      const link = document.createElement('a');
      const body = 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);
  }
}
export default globalDownload;
 
 
原文地址:https://www.cnblogs.com/HePandeFeng/p/12887490.html