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

时间:2016-07-03 03:25:03

标签: download angular

我有一个按钮定义为:

<button pButton type="button" label="Download" data-icon="fa-cloud-download" (click)="download()"></button>

download方法委托给服务,服务使用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”。

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

如何正确下载文件?...如果不可能,有可用的解决方法吗?

2 个答案:

答案 0 :(得分:5)

这是一个简单的工作示例 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>

答案 1 :(得分:4)

我终于使用答案中解释的技巧解决了问题:https://stackoverflow.com/a/37051365/2011421

我在这里描述我的具体方法以防万一:

download(model:GlobalModel) {
    // Xhr creates new context so we need to create reference to this
    let self = this;
    var pending:boolean = true;

    // Create the Xhr request object
    let xhr = new XMLHttpRequest();

    let url = BASE + "/download";
    xhr.open('POST', url, true);
    xhr.setRequestHeader("Content-type", "application/json");
    xhr.responseType = 'blob';

    // Xhr callback when we get a result back
    // We are not using arrow function because we need the 'this' context
    xhr.onreadystatechange = function () {

        // We use setTimeout to trigger change detection in Zones
        setTimeout(() => {
            pending = false;
        }, 0);

        // If we get an HTTP status OK (200), save the file using fileSaver
        if (xhr.readyState === 4 && xhr.status === 200) {
            var blob = new Blob([this.response], {type: 'application/zip'});
            saveAs(blob, 'project.zip');
        }
    };

    // Start the Ajax request
    xhr.send(JSON.stringify(model));
}

不幸的是,angular2 http对象到目前为止还没有完成,这个解决方案虽然有用,但感觉很糟糕。