ajaxでファイルストリームを取得するには

Ajaxでファイルストリームを取得するには、XMLHttpRequestオブジェクトのresponseTypeプロパティをblobに設定し、responseプロパティからファイルストリームのデータを取得します。

以下にサンプルコードを示します。

var xhr = new XMLHttpRequest();
xhr.open('GET', 'example.com/file.pdf', true);
xhr.responseType = 'blob';

xhr.onload = function(e) {
  if (this.status == 200) {
    var blob = new Blob([this.response], {type: 'application/pdf'});
    // 处理文件流,比如使用 FileReader 进行读取或者直接下载
    var reader = new FileReader();
    reader.onloadend = function() {
      console.log(reader.result);
    };
    reader.readAsText(blob);
  }
};

xhr.send();

上記の例では、xhr.responseType プロパティでレスポンスのデータタイプを blob に設定し、xhr.onload コールバック関数内で this.response からファイルストリームのデータを取得できます。取得したファイルストリームは FileReader やその他の手段を使用してさらに処理できます。

bannerAds