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

Jus*_*gin 7 filesystems android file file-browser react-native

我正在使用React Native(0.48.3)进行Android开发.看来,我遇到了一个非常简单的任务:选择一个文件并将其内容读作字符串.我有react-native-document-picker v2.0.0用于文件选择,它工作正常:我可以选择文件并获取它的URI.问题是,我无法使用此链接创建任何包读取文件.我已经尝试过react-native-filesystemreact-native-fs,但看起来,它们只适用于应用程序目录中的文件.无论如何,我得到这样的错误:

Error: File was not found: content://com.android.providers.downloads.documents/document/7

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

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

fuj*_*471 5

假设你正在使用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)
}
Run Code Online (Sandbox Code Playgroud)

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


Ner*_*gen 0

在 Android 设备上,您需要附加“file://”才能加载任何文件。您可以使用您提到的包或手动执行此操作。如果您手动附加它,则可以使用react-native-fs来读取URI。