ajax怎么获取文件流

avatar
作者
猴君
阅读量:1

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

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!