【问题标题】:How to properly download excel file with Angular2如何使用Angular2正确下载excel文件
【发布时间】:2017-04-07 11:11:36
【问题描述】:

这是我的服务的代码,它发出带有响应的 xls 文件的发布请求:

exportInternalOrder(body) {
        let user_token: string = this.sessionService.getToken();
        let headers = new Headers();
        headers.append('responseType', 'arraybuffer');
        headers.append('Authorization', 'Bearer ' + user_token);
        return this.http.post(this.config.exportInternalOrder, body,{
            headers: headers
        }).map(res => new Blob([res._body],{ type: 'application/vnd.ms-excel' }));
    }

应该处理excel文件的响应。 这是调用它的代码:

let objToSend = this.makeObjToSend(false);
this.reportingService.exportExcel(objToSend)
    .subscribe(
        data => {
            this.exportData(data);
        },
        error => {
            this.errorFilterMsg.push({ severity: 'error', detail: 'Report exporting has failed!' });
        }
);

这是文件的保存(出于某种原因 window.open 什么都不做):

exportData(data){       
        let blob = data;
        let a = document.createElement("a");
        a.href = URL.createObjectURL(blob);
        a.download = 'fileName.xls';
        document.body.appendChild(a);
        a.click();        
    }

但文件仍保存为损坏的文件。在使用邮递员和卷曲时,它就可以了。任何帮助将不胜感激。

【问题讨论】:

标签: excel angular content-type angular2-http


【解决方案1】:

responseType 不应该在headers 中设置,它是RequestOptionsArgs 对象的一部分,它作为post 函数中的第二个参数传递,RequestOptionsArgs 包含headersresponseType 和其他人,你可以阅读更多关于它的信息here。所以,你的代码应该是这样的:

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

exportInternalOrder(body) {
    let user_token: string = this.sessionService.getToken();
    let headers = new Headers();
    headers.append('Authorization', 'Bearer ' + user_token);
    return this.http.post(this.config.exportInternalOrder, body,{
        headers: headers,
        responseType: ResponseContentType.Blob
    }).map(res => new Blob([res._body],{ type: 'application/vnd.ms-excel' }));
}

【讨论】:

  • 我的塞尔维亚邻居朋友!!!你无法想象这篇文章对我的帮助有多大!感谢感谢,再次感谢!
  • 我正在这样做:return this.http.post(endpoint, body, {responseType: ResponseContentType.Blob}).map( (res) => { return res.blob() } );但是我收到了这个错误:“Type ResponseContentType.Blob is notassignable to type json”...有什么想法吗??
【解决方案2】:

我正在写这篇文章。它对正在寻找 Angular 2 解决方案以实现文件下载功能的其他人有所帮助。下面的代码对我有用。

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

exportInternalOrder(body) {
    let user_token: string = this.sessionService.getToken();
    let headers = new Headers();
    headers.append('Authorization', 'Bearer ' + user_token);
    return this.http.post(this.config.exportInternalOrder, body,{
        headers: headers,
        responseType: ResponseContentType.Blob}).map(res => new Blob([res.blob()],{ type: 'application/vnd.ms-excel' }));
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-26
    • 2020-02-18
    • 2020-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多