I'm using the new FileReader API to read in a file as an ArrayBuffer. I then create a "view" into that ArrayBuffer via UInt32Array to work with another API.
The problem is that my files aren't necessarily multiples of 4 bytes, and Chrome throws an error ("Uncaught RangeError: bofyshould be a multiple ofe") when I try to feed Uint32Array
a bad multiple. So how can I pad the ArrayBuffer
with 0s so that it bees a multiple?
var reader = new FileReader();
var pos = 0;
var xxh = XXH();
reader.onprogress = function(progress) {
// round down length to the nearest multiple of 4, save the remaining bytes for the next iteration
var length = Math.floor((progress.loaded - pos)/Uint32Array.BYTES_PER_ELEMENT);
var arr = new Uint32Array(reader.result, pos, length);
pos += length * Uint32Array.BYTES_PER_ELEMENT;
xxh.update(arr);
};
reader.onload = function() {
// `pos` will be a multiple of 4 here but the number of remaining bytes might not be. How can I pad `reader.result`?
var arr = new Uint32Array(reader.result, pos); // error occurs here
xxh.update(arr);
};
reader.readAsArrayBuffer(file);
I'm using the new FileReader API to read in a file as an ArrayBuffer. I then create a "view" into that ArrayBuffer via UInt32Array to work with another API.
The problem is that my files aren't necessarily multiples of 4 bytes, and Chrome throws an error ("Uncaught RangeError: bofyshould be a multiple ofe") when I try to feed Uint32Array
a bad multiple. So how can I pad the ArrayBuffer
with 0s so that it bees a multiple?
var reader = new FileReader();
var pos = 0;
var xxh = XXH();
reader.onprogress = function(progress) {
// round down length to the nearest multiple of 4, save the remaining bytes for the next iteration
var length = Math.floor((progress.loaded - pos)/Uint32Array.BYTES_PER_ELEMENT);
var arr = new Uint32Array(reader.result, pos, length);
pos += length * Uint32Array.BYTES_PER_ELEMENT;
xxh.update(arr);
};
reader.onload = function() {
// `pos` will be a multiple of 4 here but the number of remaining bytes might not be. How can I pad `reader.result`?
var arr = new Uint32Array(reader.result, pos); // error occurs here
xxh.update(arr);
};
reader.readAsArrayBuffer(file);
Share
Improve this question
asked Jan 4, 2014 at 10:05
mpenmpen
284k281 gold badges892 silver badges1.3k bronze badges
1 Answer
Reset to default 3Use Uint8Array instead, as it have byte precision. If you need to access the data with other types different than unsigned byte, create a DataView : new DataView(arr.buffer)
reader.onprogress = function(progress) {
var arr = new Uint8Array(reader.result, pos, length);
xxh.update(arr);
};
reader.onload = function() {
var arr = new Uint8Array(reader.result, pos);
xxh.update(arr);
};