1

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.

Program-Me-Rev
  • 6,184
  • 18
  • 58
  • 142
  • 1
    Would [react-native-fs](https://www.npmjs.com/package/react-native-fs) library work for you ? We use ```RNFS.readFile(fileUri, "base64");``` to read bin files – sushrut619 Aug 04 '22 at 14:31
  • 1
    Hi @sushrut619 It worked great. I'd tried it a number of times, but it just wasn't working. I did a copy-paste of your suggestion and it did! I would accept your answer if you'd it post it as an answer. Thank you for the reply. It helped a lot. – Program-Me-Rev Aug 05 '22 at 04:35

2 Answers2

2

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

sushrut619
  • 843
  • 8
  • 20
1

The library 'react-native-fs' has a function called read() which can read parts of a file.

read(filepath: string, length = 0, position = 0, encodingOrOptions?: any): Promise<string>

I used this function with a loop to read a whole file without putting the whole file in RAM (which is what most libraries do). My case was to upload large files (+1GB) with tus upload protocol.