温馨提示×

ajax怎么获取文件流

小亿
147
2023-12-07 22:23:22
栏目: 编程语言

在 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 或者其他方法对文件流进行进一步的处理。

0