0
0

More than 1 year has passed since last update.

XMLHttpRequestでAPIを叩きCSVをローカルにダウンロード

Posted at

ブラウザからURLにアクセスしたらファイルをダウンロードできる感じで
HTML+javascriptでCSVをレスポンスするAPIをコールしてCSVファイルをローカルにダウンロードしたい

結論

  1. レスポンスタイプをblobにする
  2. aタグをオブジェクトを生成してurlとdowndo属性を付与する
javascript
// APIのレスポンスが"Content-Type": 'text/csv'の想定
var request = new XMLHttpRequest();
request.open('GET', URL, true);
// 1. レスポンスタイプをBlobにする
request.responseType = "blob";
request.onload = function () {
  var data = this.response;
  // 2. aタグを作成してURLにBLOBをセット
  const a = document.createElement("a");
  document.body.appendChild(a);
  //csvファイル名を指定
  a.download = 'foo.csv';
  a.href = window.URL.createObjectURL(data)
  a.click();
}
request.send();

おしまい

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0