【问题标题】:Unable to download .xlsx file in the response of api call in Angular 2?无法在 Angular 2 中的 api 调用响应中下载 .xlsx 文件?
【发布时间】:2019-03-22 02:49:31
【问题描述】:

我正在尝试从角度 2 中的 api 调用的响应中下载“.xlsx”文件。作为响应,正文将数据作为 xml 格式获取。它正在下载,但打开文件后会出现文件损坏等错误。请在下面找到示例代码。

this.homeDetailViewService.downloadReport(JSON.stringify(requestBody))
            .subscribe((response) => {
                if (response) {
                    console.log(response);
                    var contentType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                    let blob = new Blob([response._body],{type:contentType});
                    let link = document.createElement('a');
                    link.href = URL.createObjectURL(blob);
                    link.download = "report.xlsx";
                    link.click();
                 }
            },
            (error) => {


                let errorObj = JSON.parse(error);
                // If theres no data then reset the model list and total
                if (errorObj.status === "error" && errorObj.message.match(/Record not found/)) {
                    this.curData = null;
                }
                this.loadingAnimation = false;                    // error path
                this.handleError(error);
            },
            () => {// onComplete                                           
            });

response._body 我正在获取如下数据

所以我不知道如何将 xml 类型的响应正文下载为“.xlsx”格式。

【问题讨论】:

    标签: angular


    【解决方案1】:

    它现在正在工作。

    我在请求对象中添加了responseType: ResponseContentType.Blob

    并在使用前将ResponseContentType导入服务文件,如下所示。

    import { ResponseContentType } from '@angular/http';
    

    在此之后没有“损坏文件错误”显示并且 excel 文件数据正常。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-21
      • 2021-08-19
      • 2017-11-10
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 2017-04-21
      • 1970-01-01
      相关资源
      最近更新 更多