簡體   English   中英

從HttpClient發布響應保存CSV文件

[英]Save csv file from HttpClient post response

我有一個網站,用戶可以在其中請求一些數據作為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將沒有足夠的空間來保存數據。

設法使用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')});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM