从HttpClient发布响应保存CSV文件

时间:2018-11-20 10:58:12

标签: angular csv angular-httpclient

我有一个网站,用户可以在其中请求一些数据作为csv文件。然后,数据将按原样返回,并应下载/保存到文件中。

我正在发送发布请求并进行订阅,但是每次catch方法似乎都失败了。

请求标头,已删除的授权等:

POST /api/@£$ HTTP/1.1
Connection: keep-alive
Content-Length: 144
Accept: application/json, text/plain, */*
Origin: https://@£$
Authorization: @£$
Content-Type: application/json
Accept-Encoding: gzip, deflate, br
Accept-Language: en-GB,en;
  

其主体包含参数,因此响应正确。

响应:

HTTP/1.1 200 OK
Transfer-Encoding: chunked
Content-Type: text/csv
Content-Encoding: gzip
Vary: Origin,Accept-Encoding
Server: Kestrel
Access-Control-Allow-Credentials: true
Access-Control-Allow-Origin: 
Request-Context: 
Content-Disposition: attachment; filename=export_20181120_103716.csv
X-Powered-By: ASP.NET
Set-Cookie: 
Date: Tue, 20 Nov 2018 10:37:16 GMT

我缺少一些重要的东西吗?我需要设置响应类型吗?此api仅会返回csv文件数据,因此实际上不需要检查文件类型。

编辑: 添加发送请求的代码。

dataExport(parameters) {

    const send = {
        'id': parameters.ids,
        'from': parameters.from,
        'to': parameters.to
    };

    this.adalService.post(url, send,
  { headers: new HttpHeaders({ 'Authorization': `Bearer ${token}`, 'Content-Type': 'application/json'}) })
        .do(() => { this.success('success'); })
        .catch((error) => {
            this.error(error);
            return Observable.of(null);
        })
        .subscribe(r => {
            const blob = new Blob([r], {type: 'text/csv'});
            const url = window.URL.createObjectURL(blob);
            window.open(url);
        });

}
  

编辑:将responseType: 'text'添加到了后请求中。由于响应格式错误,因此不会触发捕获。这是正确的类型吗?打字稿不允许我使用text / csv或application / csv。我担心当文件变得很大时,blob将没有足够的空间来保存数据。

1 个答案:

答案 0 :(得分:0)

设法使用responseType标头以及文件保护程序npm包解决了我的问题。目前该解决方案是可行的,但是由于这是用户选择的数据,因此文件大小可能会变得很大...

  ...post(url, send,
        { headers: new HttpHeaders({ 'Authorization': `Bearer ${token}`, 'Content-Type': contentType  }), observe: 'response', responseType: 'text'})
  .subscribe(r => { saveAs(new Blob([r.body], { type: 'text/csv' }), 'download.csv')});
相关问题