gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 16:42:44 27 4
gpt4 key购买 nike

在 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)!!当我使用 console.log(data[i]) 时,charCodeAt(i) 也为它们返回 65533 输出为“�”。

我测试了 "±".charCodeAt(0),输出是 261,所以我猜问题出在 get 接收到的data 中方法不在 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();

关于javascript - 从服务器获取文件并将其转换为javascript中的字节数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31696660/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com