ajax怎么获取文件流

   2025-02-13 2470
核心提示:在 Ajax 中获取文件流可以通过使用 XMLHttpRequest 对象的 responseType 属性来设置为 blob,然后通过 response 属性获取文件流

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

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言