• 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');
  • 相关阅读:
    request相关
    C#请求接口
    qml_base
    web
    entry
    listbox
    Canvas
    pickle
    c#枚举
    数据结构——树
  • 原文地址:https://www.cnblogs.com/huangmin1992/p/13292966.html
Copyright © 2020-2023  润新知