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 ...
var bytes = []; var reader = new FileReader(); reader. onload = function () { bytes = reader. result; }; reader. readAsArrayBuffer(myFile);
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.
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.
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;
};
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With