简体   繁体   English

从Blob读取ArrayBuffer的数据错误

[英]Reading ArrayBuffer from Blob has wrong data

I defined a simple Uint8Array with values [0,1,2,3]. 我定义了一个简单的Uint8Array,其值为[0,1,2,3]。 Then I made a Blob object with this binary data, and read from fileReader with readAsArrayBuffer method. 然后,我使用此二进制数据制作了一个Blob对象,并使用readAsArrayBuffer方法从fileReader中进行读取。 But when I got the values from blob, it contains [48, 49, 50, 51], not [0,1,2,3]! 但是当我从blob获取值时,它包含[48,49,50,51],而不是[0,1,2,3]!

This is the source code: 这是源代码:

var bin = new Uint8Array(4);
bin[0] = 0;
bin[1] = 1;
bin[2] = 2;
bin[3] = 3;
console.log(bin);    // [0,1,2,3]

var blob = new Blob(bin);

var fileReader = new FileReader();
fileReader.onload = function() {
    var buffer = fileReader.result;
    var dv = new DataView(buffer);
    console.log(new Uint8Array(buffer));    // [49,50,51,52]

    var dv = new DataView(buffer);
    console.log([
        dv.getUint8(0),
        dv.getUint8(1),
        dv.getUint8(2),
        dv.getUint8(3)
    ]);    // it also prints [49,50,51,52]
    };
};

fileReader.readAsArrayBuffer(blob);

Why this is happening? 为什么会这样呢? I wrote 0,1,2,3 but every value were added 48 more. 我写了0、1、2、3,但每个值又增加了48个。 Is there a something that I missed? 有什么我想念的吗?

The Blob constructor takes an array of arrays . Blob 构造函数采用数组数组 Right now you're passing it a single Uint8Array which it tries to convert to text. 现在,您正在传递给它一个试图转换为文本的Uint8Array。 (You can see the chars 49,50,51,51 translates to textual/ASCII representation of 1,2,3 and 4). (您可以看到chars 49,50,51,51转换为1,2,3和4的文本/ ASCII表示形式)。

To correct simply change this line to embed bin in an array - although the typed array is technically an array it will need a regular array to hold/reference the various data regardless of what the data is: 要进行更正,只需更改此行即可将bin嵌入数组中-尽管从技术上来说,类型化数组是一个数组,但无论数据是什么,都将需要一个常规数组来保存/引用各种数据:

var blob = new Blob([bin]);

I would recommend using a mime-type as well but is not really needed in this case. 我建议也使用mime类型,但在这种情况下并不需要。

 var bin = new Uint8Array(4); bin[0] = 0; bin[1] = 1; bin[2] = 2; bin[3] = 3; console.log(bin); // [0,1,2,3] var blob = new Blob([bin]); // !! <- make sure this is passed an array var fileReader = new FileReader(); fileReader.onload = function() { var buffer = fileReader.result; var dv = new DataView(buffer); console.log(new Uint8Array(buffer)); var dv = new DataView(buffer); console.log([ dv.getUint8(0), dv.getUint8(1), dv.getUint8(2), dv.getUint8(3) ]); }; fileReader.readAsArrayBuffer(blob); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM