Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - File uploading, readAsArrayBuffer?

i'm currently trying to upload a file to my server. But i'm not really sure how to do this with readAsArrayBuffer. This works if I use readAsBinaryString.

If i try to console.log it only returns 'arrayBuffer: {}'. After I've tried to upload it, i can see inside post that only a empty object was sent. If I use readAsBinaryString, I see a bunch of binary code.

var file = document.getElementById('my_file').files[0],
    reader = new FileReader();

    reader.onloadend = function(e){
        console.log(e.target.result);
        $scope.image = e.target.result;
    }

    reader.readAsArrayBuffer(file);

How can I see my file, so I know it's working when using readAsArrayBuffer? If more code is needed let me know! Thanks.

like image 866
Cheese Puffs Avatar asked Nov 15 '14 13:11

Cheese Puffs


1 Answers

According to ArrayBuffer documentation

You can not directly manipulate the contents of an ArrayBuffer; instead, you create one of the typed array objects or a DataView object which represents the buffer in a specific format, and use that to read and write the contents of the buffer.

So as I commented before probably console.log doesn't know how to represent the buffer and therefore it simply outputs arrayBuffer: {}.

If you want to show something in the console you need to use a typed array or a DataView. For example using an Int8Array:

reader.onloadend = function (e) {
    console.log(e);
    console.log(new Int8Array(e.target.result));
};

See demo

like image 196
dreyescat Avatar answered Sep 22 '22 12:09

dreyescat