1

I want to read a file input as a binary string. Therefore I have written a binary string reader (following this post), but I get the error message:

Unhandled Rejection (TypeError): Failed to execute 'readAsBinaryString' on 'FileReader': parameter 1 is not of type 'Blob'.

Reader:

ReadAudioasBinaryString(e) {
    const audio = 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.readAsBinaryString(audio);
    }, console.log (audio));
} 

Input

<div className="form-group">
         <label>Audio</label>
            <input
              className="form-control"
              type="file"
              name="audio"
              onChange={this.ReadAudioasBinaryString}
              ref={this.inputRef} //
           />
</div>

Happy for every hint!

dan_boy
  • 1,735
  • 4
  • 19
  • 50
  • I guess you want `const audio = e.target.files[0];` or something like that? And if that works, your resolving result is currently discarded. What is the end goal? What's supposed to happen with the audio file selected by the user? –  May 07 '20 at 10:06
  • Exactly. The goal is that the user inserts a file, this file should be read as a binary string. Because the backend needs files as binary string. So somehow I have to convert the file into a binary format. This is what this function `ReadAudioasBinaryString` is supposed to do. See also this post [link](https://stackoverflow.com/questions/56001073/how-to-get-byte-array-from-a-file-in-reactjs) – dan_boy May 07 '20 at 10:15
  • Ok, so did you try the change I suggested (which is what it says in the accepted answer btw, not sure why you changed it to `.name`?) Anyway, you can ditch the Promise wrapper, just use `this.setState({ binaryString: event.target.result })` in the `onload`. –  May 07 '20 at 10:20
  • Thanks a lot for your answer. Yes i changed the code as you suggested to `const audio = e.target.files[0];` (see also the updated post). Unfortently The error messages stays the same. – dan_boy May 07 '20 at 14:40
  • Here's example code that'll display the binary string: https://codesandbox.io/s/frosty-worker-w3fwb?file=/src/App.js –  May 07 '20 at 19:53
  • Hi @ChrisG it works thank you! if you post it as a post i could might accpet it as an answer. Anyway many thanks, it helped me a lot! – dan_boy May 08 '20 at 17:36

0 Answers0