Skip to content Skip to sidebar Skip to footer

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 worki

Solution 1:

This approach worked for me:

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

    returnnewPromise((resolve, reject) => {
        const reader = newFileReader();

        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

Solution 2:

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 = newFileReader();
    let file = e.target.files[0];
    console.log(file); //I can see the file's info
    reader.onload= () => {
        var array = newUint32Array(reader.result); // read the actual file contentsconsole.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)
}

Solution 3:

Just to add to tomericco's answer, here is one with few more lines to get the actual final byte array :

const test_function = async () => {

      ... ... ...

      constget_file_array = (file) => {
          returnnewPromise((acc, err) => {
              const reader = newFileReader();
              reader.onload = (event) => { acc(event.target.result) };
              reader.onerror = (err)  => { err(err) };
              reader.readAsArrayBuffer(file);
          });
       }
       const temp = awaitget_file_array(files[0])
       console.log('here we finally ve the file as a ArrayBuffer : ',temp);
       const fileb = newUint8Array(fileb)

       ... ... ...

  }

where file is directly the File object u want to read , this has to be done in a async function...

Post a Comment for "How To Get Byte Array From A File In Reactjs"