从内容 uri 读取文件时出现权限错误 [英] Permission error when reading file from content uri
问题描述
我一直在尝试制作一个简单的文档选择器,它允许用户选择一个文件并返回以 base64 编码的所选文件.为此,我目前正在使用两个包:
I've been trying to make a simple document picker that allows the user to select a file and returns the selected file encoded in base64. For that, I'm currently using two packages :
- react-native-document-picker,其中允许用户选择一个文件并返回一个内容 uri
- react-native-fs,因为它的 readFile 函数接受一个 uri参数并返回 base64 格式的文件
- react-native-document-picker, which allows the user to pick a file and returns a content uri
- react-native-fs, for its readFile function that takes an uri in parameter and returns the file in base64
这是一段特定的代码:
DocumentPicker.pick({
type: [DocumentPicker.types.allFiles]
})
.then(res =>
{
RNFS.readFile(decodeURIComponent(res.uri), "base64").then(result =>
{
console.log(result)
})
})
.catch(error =>
{
console.log(error)
})
从我的下载"文件夹中选择文件时效果很好,但是,当我尝试从最近"文件夹或与我的应用程序无关的任何文件夹中选择文件时,readFile 失败并显示错误:
It works well when selecting a file from my Downloads folder, however, when I try to select a file from the "Recent" folder or from any folder that isn't related to my app, the readFile fails with the error :
权限拒绝:读取 com.android.providers.media.MediaDocumentsProvider uri content://com.android.providers.media.documents/document/image:105724 from pid=22663, uid=10471 需要 android.permission.MANAGE_DOCUMENTS, 或 grantUriPermission()
Permission Denial: reading com.android.providers.media.MediaDocumentsProvider uri content://com.android.providers.media.documents/document/image:105724 from pid=22663, uid=10471 requires android.permission.MANAGE_DOCUMENTS, or grantUriPermission()
据我所知,MANAGE_DOCUMENTS 是一个签名"权限,不能添加到 manifest.xml 或由 react native android 权限 API 授予.
From what I've read, MANAGE_DOCUMENTS is a "signature" permission and cannot be added to the manifest.xml or granted by the react native android permission API.
有什么方法可以授予或传递 react-native-fs 此权限,或者我可以使用任何解决方法来选择没有错误的任何文件?我这样做错了吗?我尝试使用 react-native-get-real-path 从内容 uri 中获取文件 uri 并获取内容 uri 以获取 blob,但它似乎不起作用.
Is there any way I can grant or pass react-native-fs this permission, or any workaround I could use to pick any file without the error ? Am I doing this wrong ? I've tried using react-native-get-real-path to get a file uri from the content uri and fetching the content uri to get a blob, but it doesn't seem to work.
谢谢
推荐答案
自从发现问题就回答我的问题:RNFS.readFile 仅在提供原始 res.uri 时才有效,您不必通过 decodeURIComponent 对其进行解码.
Answering my question since I found the problem : RNFS.readFile only works when supplied the original res.uri, you don't have to decode it via decodeURIComponent.
正确的代码是:
RNFS.readFile(res.uri, "base64").then(result =>
{
console.log(result)
})
这篇关于从内容 uri 读取文件时出现权限错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!