Javascript - get data out of ArrayBuffer?

Ben picture Ben · Jun 8, 2012 · Viewed 14.6k times · Source

I've got a drag and drop script that uses readAsArrayBuffer(). The length of the buffer is perfect, but I can't seem to figure out how to pull the data out of the buffer.

Apparently I've got to make a DataView or an Uint8Array or something, then iterate through its byteLength...help!

EDIT Pertinent code (there's not much of it):

var reader = new FileReader();
reader.onload = function(e) {
    // do something with e.target.result, which is an ArrayBuffer
} 
reader.readAsArrayBuffer(someFileHandle);

Answer

haylem picture haylem · Jun 8, 2012

This might change based on your answer to my comment, but if I assume that you are using a FileReader somewhere, you need to read it's result attribute in the loaded callback that you need to provide:

function loaded(evt) {  
  var datastring = evt.target.result;

  // do something here
}

reader.onload = loaded; // where reader is a FileReader, FileReaderSync 

Update: Ah, I see. Well then your best course of action is to follow to this duplicate:

Converting between strings and ArrayBuffers

Update2: Note that you could probably use readAsText() then, but I don't know if you're at liberty to do this.