post 請求,responseType為blob,后端返回文件流,前端進行轉換下載


1.請求接口時,請求類型設置為blob;responseType:'blob';

2.將后端返回的文件流進行轉換為ulr,新開窗口下載

 let reader = new FileReader(); // 創建讀取文件對象
                let result: any;
                reader.addEventListener('loadend', () => {
                  if (typeof reader.result === 'string') {
                    try {
                      result = JSON.parse(reader.result);
                    } catch (e) {
                      result = undefined;
                    }
                  } // 返回的數據
                  if (result && result.code) {
                    this.message.error(result.message);
                    this.packageDownloadVisible = false;
                    return;
                  }
                  const date = formatDate(new Date(), 'yyyy-MM-dd HH :mm', 'zh-CN');
                  let blob = new Blob([res], {type: 'application/zip'});
                  if (window.navigator.msSaveOrOpenBlob) {
                    if (navigator.userAgent.indexOf('Firefox') >= 0
                      // @ts-ignore
                      || (navigator.userAgent.toLocaleLowerCase().indexOf('trident')) >= 0) {
                      navigator.msSaveBlob(blob, date + ' ' + this.translate.instant('package-files') + '.zip');
                    } else {
                      navigator.msSaveBlob(blob, date + ' ' + this.translate.instant('package-files'));
                    }
                  } else {
                    const link = document.createElement('a');
                    const body = document.querySelector('body');
                    link.href = window.URL.createObjectURL(blob);
                    link.download = date + ' ' + this.translate.instant('package-files');
                    // fix Firefox,ie11
                    if (navigator.userAgent.indexOf('Firefox') >= 0
                      // @ts-ignore
                      || (navigator.userAgent.toLocaleLowerCase().indexOf('trident')) >= 0) {
                      link.download = date + ' ' + this.translate.instant('package-files') + '.zip';
                    }
                    link.style.display = 'none';
                    body.appendChild(link);
                    link.click();
                    body.removeChild(link);
                    window.URL.revokeObjectURL(link.href);

                  }
                  this.packageDownloadVisible = false;
                });
                reader.readAsText(res, 'utf-8');

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM