angular5+==>post下载文件

2020-12-27  本文已影响0人  小米和豆豆
import { HttpClient, HttpHeaders } from '@angular/common/http';
......

 downLoadFile(url: any, data: any, fileName: any) {
    return new Promise((resolve,reject) => {
      this.httpClient.post(url, data, {
        headers: new HttpHeaders().set('Authorization', ''),
        responseType: 'blob',
        observe: 'response'
      }).subscribe(res => {
        // var resHeaders = res.headers.toJSON() || {};
        /**
         * 关于Blob 如何获取内容
         * https://developer.mozilla.org/zh-CN/docs/Web/API/Blob
         * reader.result 包含转化为类型数组的blob
         */
        var reader: any = new FileReader();
        reader.readAsText(res.body, 'utf-8');
        // reader.readAsArrayBuffer(res.body);
        reader.addEventListener("loadend", () => {
          let toJson;

          try {
            /**
             * 尝试将接口返回的数据转换成json格式
             * 接口正常情况下返回的数据流的形式,转成json数据肯定会报错。
             * catch捕获后执行文件下载。
             *
             * 假如能够顺利转成json,说明接口是报错状态,返回的是错误数据
             */
            toJson = JSON.parse(reader.result)

          } catch (error) {
            /*
             * 获取reseponse headers中的 文件名
             */
            let disposition = res.headers.get('content-disposition');
            let newfileName = '';
            if (disposition) {
              newfileName = decodeURI(disposition.split('=')[1]);
              fileName = newfileName;
            }
            resolve('success');
            this.downFile(res.body, fileName);
            return null;
          }
          //报错
          reject({
            status: 400,
            error_msg: toJson.msg || toJson.message || '下载错误'
          });
        });
      },err=> {
          reject({
            status: err.status,
            error_msg: err.message
          });
      })
    });
  }
  downFile(blob, fileName) {
    if (fileName === "test") {};
    if (window.navigator.msSaveOrOpenBlob) {
      navigator.msSaveBlob(blob, fileName);
    } else {
      var link = document.createElement('a');
      link.href = window.URL.createObjectURL(blob);
      link.download = fileName;
      link.click();
      window.URL.revokeObjectURL(link.href);
    }
  }
上一篇下一篇

猜你喜欢

热点阅读