react-nativefilewebrtcbytestream

How to read a selected file to Bytes or into a Stream


I'm trying to send a file selected using react-native-document-picker over WebRTC, but I can't seem to get to reading it to bytes.

In a browser I would use a FileReader to read from<input type="file">.

document.querySelector('input').addEventListener('change', function() {
  var reader = new FileReader();
  reader.onload = function() {

    var arrayBuffer = this.result,
      array = new Uint8Array(arrayBuffer),
      binaryString = String.fromCharCode.apply(null, array);

    console.log(binaryString);

  }
  reader.readAsArrayBuffer(this.files[0]);

}, false);  

In React Native I select a file as follows :

import DocumentPicker from 'react-native-document-picker';

const handleDocumentSelection = useCallback(async () => {
    const file = await DocumentPicker.pick({
        presentationStyle: 'fullScreen',
    });

    // Send file via WebRTC
}, []);

How would I go about reading a file to bytes in React Native?

Thank you all in advance.


Solution

  • We use react-native-fs to read a binary file in our react-native app.

    Import it as
    const RNFS = require("react-native-fs");
    and then read file as
    const fileBin = await RNFS.readFile(otaFileUri, "base64");

    Furthermore, to convert it back into bytes(Uint8Array) we use rfc4648