Getting byte array through input type = file

stacknist picture stacknist · Sep 14, 2015 · Viewed 158.5k times · Source

I am using ajax call to post byte[] value of a input type = file input to web api which receives in byte[] format. However, I am experiencing difficulty of getting byte array. I am expecting that we can get the byte array through File API.

Note: I need to store the byte array in a variable first before passing through ajax call

Answer

Kaiido picture Kaiido · Sep 14, 2015

[Edit]

As noted in comments above, while still on some UA implementations, readAsBinaryString method didn't made its way to the specs and should not be used in production. Instead, use readAsArrayBuffer and loop through it's buffer to get back the binary string :

document.querySelector('input').addEventListener('change', function() {

  var reader = new FileReader();
  reader.onload = function() {

    var arrayBuffer = this.result,
      array = new Uint8Array(arrayBuffer),
      binaryString = String.fromCharCode.apply(null, array);

    console.log(binaryString);

  }
  reader.readAsArrayBuffer(this.files[0]);

}, false);
<input type="file" />
<div id="result"></div>

For a more robust way to convert your arrayBuffer in binary string, you can refer to this answer.


[old answer] (modified)

Yes, the file API does provide a way to convert your File, in the <input type="file"/> to a binary string, thanks to the FileReader Object and its method readAsBinaryString.
[But don't use it in production !]

document.querySelector('input').addEventListener('change', function(){
    var reader = new FileReader();
    reader.onload = function(){
        var binaryString = this.result;
        document.querySelector('#result').innerHTML = binaryString;
        }
    reader.readAsBinaryString(this.files[0]);
  }, false);
<input type="file"/>
<div id="result"></div>

If you want an array buffer, then you can use the readAsArrayBuffer() method :

document.querySelector('input').addEventListener('change', function(){
    var reader = new FileReader();
    reader.onload = function(){
        var arrayBuffer = this.result;
      console.log(arrayBuffer);
        document.querySelector('#result').innerHTML = arrayBuffer + '  '+arrayBuffer.byteLength;
        }
    reader.readAsArrayBuffer(this.files[0]);
  }, false);
<input type="file"/>
<div id="result"></div>