微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

带有发布请求的angular2下载文件

我有一个按钮定义为:
<button pButton type="button" label="Download" data-icon="fa-cloud-download" (click)="download()"></button>

下载方法委托给服务的地方,服务使用post方法调用api:

download(model:GlobalModel) {
        let downloadURL = base + "rest/process/download";
        let body = JSON.stringify(model);
        let headers = new Headers({'Content-Type': 'application/json'});
        let options = new RequestOptions({headers: headers});   

        this.http.post('http://localhost:48080/rest/process/download',body,options)
            .toPromise()
            .then(
                response => {
                    console.log(response);       
                    var mediaType = 'application/zip';
                    var blob = new Blob([response.blob()],{type: mediaType});
                    var filename = 'project.zip';
                    saveAs(blob,filename);//FileSaver.js libray
                });

    }

但到目前为止还没有实现blob()方法,并且还有其他使用_body的答案,但是有一个打字稿错误,比如“_body is private”.

浏览器显示下载窗口,但是当我下载文件时已损坏且无法打开它(我检查邮递员并且文件是从服务器生成的).

我怎样才能正确下载文件?…如果不可能,有可用的解决方法吗?

这是一个工作的例子
https://stackoverflow.com/a/42992377/3752172

将控制器修改为POST:

[HttpPost("realisationsFilterExcel")]
public FileResult exportExcell([FromBody] FilterRealisation filter)
{
    var contentType = "application/octet-stream";
    HttpContext.Response.ContentType = contentType;

    PaginationSet<RealisationReportviewmodel> itemsPage = _realisationRepository.GetRealisationReportFilter(filter,User);

    RealisationsReportExcell reportExcell = new RealisationsReportExcell();
    var filedata = reportExcell.GetReport(itemsPage);   
    FileContentResult result = new FileContentResult(filedata,contentType)
    {
        FileDownloadName = "report.xlsx"
    };
    return result;
}

需要FileSaver作为dep:

npm install file-saver --save 
npm install @types/file-saver --save

方法DownloadComponent angular2修改为POST

@input() filter: any;

public downloadFilePost() {
        this.http.post(this.api,this.filter,{ responseType: ResponseContentType.Blob })
        .subscribe(
        (response: any) => {
            let blob = response.blob();
            let filename = 'report.xlsx';
            FileSaver.saveAs(blob,filename);
        });
    }

运用

<download-btn [filter]="myFilter" api="api/realisations/realisationsFilterExcel"></download-btn>

原文地址:https://www.jb51.cc/angularjs/142090.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐