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

问题描述

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

但是需要读取文件 react-native-fs 的 base64 内容,该文件存在依赖性问题(需要 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(本地路径),然后您就可以开始滚动了。