【问题标题】:Permission error when reading file from content uri从内容 uri 读取文件时出现权限错误
【发布时间】:2019-07-07 03:41:11
【问题描述】:

我一直在尝试制作一个简单的文档选择器,它允许用户选择一个文件并返回以 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 失败并出现错误:

Permission Denial:从 pid=22663 读取 com.android.providers.media.MediaDocumentsProvider uri content://com.android.providers.media.documents/document/image:105724,uid=10471 需要 android.permission.MANAGE_DOCUMENTS , 或 grantUriPermission()

根据我的阅读,MANAGE_DOCUMENTS 是“签名”权限,不能添加到 manifest.xml 或由 react native android 权限 API 授予。

有什么方法可以授予或传递 react-native-fs 此权限,或者我可以使用任何解决方法来选择任何文件而不会出现错误?我做错了吗? 我尝试使用 react-native-get-real-path 从内容 uri 获取文件 uri 并获取内容 uri 以获取 blob,但它似乎不起作用。

谢谢

【问题讨论】:

    标签: android react-native


    【解决方案1】:

    在我发现问题后回答我的问题:RNFS.readFile 仅在提供原始 res.uri 时才有效,您不必通过 decodeURIComponent 对其进行解码。

    正确的代码是:

    RNFS.readFile(res.uri, "base64").then(result =>
    {
        console.log(result)
    })
    

    【讨论】:

    • 我需要 decodeURIComponent for iOS 所以我使用它取决于平台
    【解决方案2】:

    对于遇到此问题的任何人,请确保您不要将 decodeURIComponent 用于 Android。但是您仍然必须将其用于IOS。以下代码 sn-p 可在两个平台上运行

    import { Platform } from 'react-native';
    import DocumentPicker from 'react-native-document-picker';
    
    const file = await DocumentPicker.pick();
    const uri = Platform.select({
      android: file.uri,
      ios: decodeURIComponent(file.uri)?.replace?.('file://', ''),
    });
    
    const base64File = await RNFS.readFile(uri, "base64");
    // Your file handling here
    

    【讨论】:

      猜你喜欢
      • 2021-02-17
      • 2017-06-26
      • 1970-01-01
      • 2018-10-13
      • 1970-01-01
      • 1970-01-01
      • 2014-06-06
      • 1970-01-01
      • 2021-03-03
      相关资源
      最近更新 更多