从服务器获取文件并将其转换为javascript中的字节数组

Get file from server and convert it to byte array in javascript?

本文关键字:javascript 字节 数组 字节数 转换 获取 服务器 文件      更新时间:2023-09-26

在javascript中,我想从服务器下载(获取)二进制文件并使用其字节。我使用以下代码:

$.get('/file.mp4', function(data) {
    var bytes = new Uint8Array(data.length);
    for (var i=0; i<data.length; i++) {
            bytes[i] = data.charCodeAt(i);
        }
    });

但是有一个问题:data变量的一些字符的ASCII码大于255(如" --> ASCII:261)!!和charCodeAt(i)返回65533也为他们,当我使用console.log(data[i])输出是" "

我测试了"ą".charCodeAt(0)和输出261,所以我猜问题是在数据接收的get方法而不是在charCodeAt方法。有没有其他方法下载二进制文件??

像这样获取数据:

var xhr = new XMLHttpRequest();
xhr.open('GET', '/my/image/name.png', true);
xhr.responseType = 'blob';
xhr.onload = function(e) {
  if (this.status == 200) {
    // get binary data as a response
    var blob = this.response;
  }
};
xhr.send();