react-nativefile-uploadreact-native-fsrn-fetch-blob

Unable to read file contents in react-native >0.59


I want to upload documents in my react native app and for that I am using react-native-document-picker

But to read the base64 content of the file react-native-fs is needed which has a dependency issue (needs react-native v0.59)

I am unable to install it, as I have react-native v 0.63

Getting the following error as I install it:

admin@Salvis-MacBook project % npm install react-native-fs --save
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: project@0.0.1
npm ERR! Found: react-native@0.63.0
npm ERR! node_modules/react-native
npm ERR!   react-native@"0.63.0" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer react-native@"^0.59.5" from react-native-fs@2.16.6
npm ERR! node_modules/react-native-fs
npm ERR!   react-native-fs@"*" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR! 
npm ERR! See /Users/admin/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/admin/.npm/_logs/2021-01-25T09_41_08_842Z-debug.log

Please suggest something if you ran onto the same issue.

I tried reading contents using rn-fetch-blob and it's working fine on Android but I am unable to read file in ios simulator (I downloaded some sample pdf file from safari)

Whenever I try to read the file, it says file not found.

I have also tried below methods:

uri.replace('file://', '')
uri.replace('file:', '')
decodeURIComponent(uri)

but still unable to read it on ios


Solution

  • Seems like there is an issue with react-native-fs (there is an open issue: check here)

    So I found an alternate solution to read to contents(base64) of a file. Just use the readFile() function of rn-fetch-blob instead.

    In your function where you need to pass the base64 string, just do:

    const fs = RNFetchBlob.fs;
    let Base64String = await fs.readFile(yourFileObject.uri, 'base64');
    

    yourFileObject is the object you get when you pick any file through react-native-document-picker

    You can use any picker of your choice, just you need to pass the file uri(local path) in the readFile() function and you are ready to roll.