5

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.

Cheese Puffs
  • 955
  • 3
  • 10
  • 19
  • 1
    Try to log the length of the buffer `console.log(e.target.result.byteLength)`. The code is likely to be working but the console representation of an `ArrayBuffer` is just `arrayBuffer: {}`, and not a bunch of binary stuff. – dreyescat Nov 15 '14 at 15:17
  • dreyescat - Thanks, yes, now I get some output! – Cheese Puffs Nov 15 '14 at 15:39

2 Answers2

9

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

dreyescat
  • 13,558
  • 5
  • 50
  • 38
0

If you want to upload am image then you have to convert it into base64 format. You can do it either by using canvas element or by using Filereader.If you are using Filereader then you have to use readAsDataURL()

You can refer MDN for this https://developer.mozilla.org/en-US/docs/Web/API/FileReader.readAsDataURL

also you can use canvas element Convert an image to canvas that is already loaded

Community
  • 1
  • 1
Ajeet Lakhani
  • 3,768
  • 2
  • 22
  • 37
  • Thanks for the reply. Yes, I'm planning on using fileReader. I'll have a form with some input fields, including a file input. Then I want to send the form data including the image with POST. Is readAsDataURL still the way to go? – Cheese Puffs Nov 15 '14 at 15:39
  • yes why not? readAsDataURL is just a way to convert image it into base64 format string. You can store it in variable and Post it in form or store it in database – Ajeet Lakhani Nov 15 '14 at 16:50