gpt4 book ai didi

android - 如何在 Android 上的 React Native 中读取带有内容 URI 的文件?

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:10:32 26 4
gpt4 key购买 nike

我正在使用 React Native (0.48.3) 进行 Android 开发。看来,我被一项非常微不足道的任务困住了:选择一个文件并将其内容作为字符串读取。我有 react-native-document-picker v2.0.0用于文件选择,它工作正常:我可以选择文件并获取它的 URI。问题是,我无法制作任何包来使用此链接读取文件。我已经试过了 react-native-filesystemreact-native-fs ,但似乎它们只能处理应用程序目录中的文件。无论如何,我得到这样的错误:

错误:找不到文件:content://com.android.providers.downloads.documents/document/7

我需要使用什么包或功能?

UPD: 检索真实路径,而不是 content:// 路径,使用 react-native-get-real-path使事情正常进行。但是这种转换真的有必要吗,是否可以使用content://路径加载文件?

最佳答案

假设您正在使用 react-native-fs,使用 copyFile 可以将内容 uri 转换为文件 uri。

if (url.startsWith('content://')) {
const uriComponents = url.split('/')
const fileNameAndExtension = urlComponents[uriComponents.length - 1]
const destPath = `${RNFS.TemporaryDirectoryPath}/${fileNameAndExtension}`
await RNFS.copyFile(uri, destPath)
}

然后你可以按预期使用'file://' + destPath

关于android - 如何在 Android 上的 React Native 中读取带有内容 URI 的文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46278019/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com