Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get byte array from a file in reactJS

I've got a form for uploading Avatar image and I have to send the image file in the format of binary string; so far I've tried ReadAsBinaryString from FileReader but it's not working:( here's my code:

<form onSubmit={this.onFormSubmit}>
      <div className="row justify-content-center mb-2">
           <input type="file" id="avatar"  accept="image/png, image/jpeg" 
            onChange={this.uploadedImage} />
           <button type="submit" className="btn btn-sm btn-info">Send</button>
       </div>
  </form>

and that is how I'm trying to use ReadAsBinaryString in uploadedImage function:

uploadedImage(e) {
    let reader = new FileReader();
    let file = e.target.files[0];
    console.log(file); //I can see the file's info
    reader.onload= () => {
        var array = new Uint32Array(file);
        console.log("_+_array:",array); // the array is empty!
        var binaryString = String.fromCharCode.apply(null,array) ;
        console.log("__binaryString:",binaryString);
      this.setState({
        file: binaryString
      },()=>{
        console.log(this.state.file);//ergo file is set to an empty image
    });
    }
    reader.readAsArrayBuffer(file)
}

so to sum it up, I get a file but I can't convert it to byte array; Is there anything wrong with this code or this approach is completely wrong?

like image 824
BlackSheep Avatar asked May 06 '19 08:05

BlackSheep


Video Answer


2 Answers

This approach worked for me:

function readFileDataAsBase64(e) {
    const file = e.target.files[0];

    return new Promise((resolve, reject) => {
        const reader = new FileReader();

        reader.onload = (event) => {
            resolve(event.target.result);
        };

        reader.onerror = (err) => {
            reject(err);
        };

        reader.readAsDataURL(file);
    });
}

You can call reader.readAsBinaryString() if you wish to use binary string. More here: https://developer.mozilla.org/en-US/docs/Web/API/FileReader

like image 93
tomericco Avatar answered Sep 20 '22 19:09

tomericco


You are trying to read the file data using the file variable which contains the file info not the file contents. Try sth like the following:

FileReader documentation

uploadedImage(e) {
    let reader = new FileReader();
    let file = e.target.files[0];
    console.log(file); //I can see the file's info
    reader.onload= () => {
        var array = new Uint32Array(reader.result); // read the actual file contents
        console.log("_+_array:",array); // the array is empty!
        var binaryString = String.fromCharCode.apply(null,array) ;
        console.log("__binaryString:",binaryString);
      this.setState({
        file: binaryString
      },()=>{
        console.log(this.state.file);//ergo file is set to an empty image
    });
    }
    reader.readAsArrayBuffer(file)
}
like image 36
Nikos M. Avatar answered Sep 22 '22 19:09

Nikos M.