I do not consider myself a programmer, so I have found many, many answers to my questions by searching this site. I have been unable to figure this one out, though.
Using Javascript (really the only language I can even attempt right now), I am trying to upload a file and load its binary data into an ArrayBuffer for editing. I am utilizing both FileSaver.js and Blob.js to increase compatibility. I have the user select the file, then load the file. When loading commences, a FileReader uses readAsArrayBuffer to load the file into an ArrayBuffer. I currently have it set to give an alert to check on the contents of the ArrayBuffer, but I will eventually remove that and simply work with the data.
If I take out the index, the alert knows that it is displaying an ArrayBuffer, but whenever I pick an index (like [0]), it tells me it's undefined. How do I get the file data into an ArrayBuffer? And how will it be divided up? Preferably I'd like 1 byte to an index.
function loadButtonPressed() {
var loadedFile = document.getElementById('loadFile').files;
var testFile = loadedFile[0];
var reader = new FileReader();
reader.onloadend = function(evt) {
if (evt.target.readyState == FileReader.DONE) {
alert(String(reader.result[0]));
}
};
reader.readAsArrayBuffer(testFile);
}
A buffer is just a series of bytes with no meaning. JS provides no way to directly manipulate a buffer. To look into a buffer, you need a view, that defines how the buffer is interpreted - either a typed array, or a DataView
object. Try this:
// ...
let buffer = reader.result;
let view = Int8Array(buffer);
console.log(view[0]);
or this:
// ...
let buffer = reader.result;
console.log(new DataView(buffer).getInt8(0))