angglarはblobバイナリストリームを使用してバックグラウンドファイルをダウンロードします。

1911 ワード

先に二つの比較的古いjsダウンロード方式を話してください。
1.window.open(src)とwindow.location=src
2.フォーム提出
これらの2つの方法には限界があり、大量のパラメータを伝えるダウンロード要求に対しては、このように書くことができる。
this.http.post(`${this.uri}/exportdata.file`, params, {responseType: 'blob'}).subscribe(data => {
  const link = document.createElement('a');
  const blob = new Blob([data], {type: 'application/zip'});
  link.setAttribute('href', window.URL.createObjectURL(blob));
  link.setAttribute('download', new Date().getTime() + '.zip');
  link.style.visibility = 'hidden';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
})
ここでは、レスポンスTypeを設定します。「blob」を使ってファイルのバイナリストリームを取得し、aタグを使ってアナログクリックでダウンロードします。
このダウンロード方式には2つの注意が必要です。
1.ダウンロードしたファイルフォーマットは確定が必要です。
上記の例はzip形式です。他のフォーマットであれば、Content-Type(コード3行目)とファイル名の拡張子(5行目)を変更する必要があります。たとえば:
 'doc        => 'アプリ/msword'は、
 'xls        => 'appication/vnd.ms-excel'は、
2.ファイル名はフロントエンドの名前ですか?バックエンドの名前ですか?
フロントエンドの名前は上のコードでいいです。バックエンドの名前が必要なら、まずバックエンドがレスポンスヘッダにファイル名を付ける必要があります。
Content-disposition: attachment; filename=file_201807201030327711.zip
上のポストに修正をお願いします。
this.http.post(`${this.uri}/exportdata.file`, params, {responseType: 'blob', observe: 'response'}).subscribe(data => {
  const link = document.createElement('a');
  const blob = new Blob([data.body], {type: 'application/zip'});
  link.setAttribute('href', window.URL.createObjectURL(blob));
  link.setAttribute('download', data.headers.get('Content-disposition').split('filename=')[1]);
  link.style.visibility = 'hidden';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
})
observe:'reponse'を設定して返信された応答ヘッダを取得し、ファイル名を取得します。