skip to Main Content

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.

2

Answers


  1. 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

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search