Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get byte array from input type file using javascript

I am generating my Html page from database (html tags are stored in database) using sql-server functions .. when generating controls I am easily able to deal with all type input controls but in case of input type "file" I am unable to get bytes of uploaded Image/File , i have a requirement of saving file/image byte into DB . Requirement -- How to get imagebytes from input type File using JavaScript , from onclick event of a input type button ...

like image 471
user2322447 Avatar asked Mar 27 '14 07:03

user2322447


People also ask

How to convert input file to byte array in JavaScript?

var bytes = []; var reader = new FileReader(); reader. onload = function () { bytes = reader. result; }; reader. readAsArrayBuffer(myFile);

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.

How do you read a file in Javascript?

To read a file, use FileReader , which enables you to read the content of a File object into memory. You can instruct FileReader to read a file as an array buffer, a data URL, or text. // Check if the file is an image.


1 Answers

This took me 8 hours to figure out lol. Here you go :)

function submitForm() {
   var fileList = document.getElementById("image").files;
   var fileReader = new FileReader();
   if (fileReader && fileList && fileList.length) {
      fileReader.readAsArrayBuffer(fileList[0]);
      fileReader.onload = function () {
         var imageData = fileReader.result;
      };
   }
}
like image 110
sellmaurer Avatar answered Oct 16 '22 11:10

sellmaurer