Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting byte array through input type = file

var profileImage = fileInputInByteArray;    $.ajax({    url: 'abc.com/',    type: 'POST',    dataType: 'json',    data: {       // Other data       ProfileImage: profileimage       // Other data    },    success: {    }  })    // Code in WebAPI  [HttpPost]  public HttpResponseMessage UpdateProfile([FromUri]UpdateProfileModel response) {    //...    return response;  }    public class UpdateProfileModel {    // ...    public byte[] ProfileImage {get ;set; }    // ...  }
<input type="file" id="inputFile" />

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

like image 399
stacknist Avatar asked Sep 14 '15 02:09

stacknist


People also ask

How to get byte array from input type file using JavaScript?

Here is one answer to get the actual final byte array , just using FileReader and ArrayBuffer : const test_function = async () => { ... ... ... const get_file_array = (file) => { return new Promise((acc, err) => { const reader = new FileReader(); reader. onload = (event) => { acc(event.

What is byte array in Javascript?

An array of bytes is known as an array buffer in javascript while known as a “byte array” in some other languages. The ArrayBuffer object represents a fixed-length raw binary data buffer whose content can't be altered directly.


2 Answers

[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>
like image 145
Kaiido Avatar answered Sep 24 '22 01:09

Kaiido


$(document).ready(function(){      (function (document) {    var input = document.getElementById("files"),    output = document.getElementById("result"),    fileData; // We need fileData to be visible to getBuffer.      // Eventhandler for file input.     function openfile(evt) {      var files = input.files;      // Pass the file to the blob, not the input[0].      fileData = new Blob([files[0]]);      // Pass getBuffer to promise.      var promise = new Promise(getBuffer);      // Wait for promise to be resolved, or log error.      promise.then(function(data) {        // Here you can pass the bytes to another function.        output.innerHTML = data.toString();        console.log(data);      }).catch(function(err) {        console.log('Error: ',err);      });    }      /*       Create a function which will be passed to the promise      and resolve it when FileReader has finished loading the file.    */    function getBuffer(resolve) {      var reader = new FileReader();      reader.readAsArrayBuffer(fileData);      reader.onload = function() {        var arrayBuffer = reader.result        var bytes = new Uint8Array(arrayBuffer);        resolve(bytes);      }    }      // Eventlistener for file input.    input.addEventListener('change', openfile, false);  }(document));  });
<!DOCTYPE html>  <html>  <head>  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  </head>  <body>    <input type="file" id="files"/>  <div id="result"></div>  </body>  </html>
like image 26
sebu Avatar answered Sep 24 '22 01:09

sebu