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');

 

posted @ 2020-07-13 14:20  面包_girl  阅读(14648)  评论(0编辑  收藏  举报
/* 鼠标点击文字特效 */