无法读取 react-native >0.59 中的文件内容

Unable to read file contents in react-native >0.59

我想在我的 React 本机应用程序中上传文档,为此我正在使用 react-native-document-picker

但要读取文件的 base64 内容 react-native-fs 是必需的,它存在依赖性问题(需要 react-native v0.59)

我无法安装它,因为我有 react-native v 0.63

安装时出现以下错误:

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

如果您运行遇到同样的问题,请提出建议。

我尝试使用 rn-fetch-blob 阅读内容,它在 Android 上运行良好,但我无法在 ios 模拟器中读取文件(我从 safari 下载了一些示例 pdf 文件)

每当我尝试读取文件时,它都会提示找不到文件。

我也试过以下方法:

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

但在 ios

上仍然无法阅读

似乎 react-native-fs 有问题(有一个未解决的问题:check here

所以我找到了另一种读取文件内容 (base64) 的解决方案。 只需使用 rn-fetch-blobreadFile() 函数即可。

在您需要传递 base64 字符串的函数中,只需执行以下操作:

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

yourFileObject是你通过react-native-document-picker

选择任何文件时得到的对象

您可以使用您选择的任何选择器,只需要在 readFile() 函数中传递文件 uri(本地路径)就可以开始了。