React Native中如何从安卓文件URI获取PDF对应的content URI
核心说明
你提到的/data/user/0/...格式路径是应用私有沙盒内的文件绝对路径,不是URI类型,以下两种方案均可满足你的需求:
方案1:生成content://格式URI(适配安卓文件访问规范)
安卓7.0及以上版本禁止对外暴露file://类型URI,必须通过FileProvider生成合法的content URI,步骤如下:
- 在
AndroidManifest.xml中注册FileProvider
<provider android:name="androidx.core.content.FileProvider" android:authorities="${applicationId}.fileprovider" android:exported="false" android:grantUriPermissions="true"> <meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="@xml/file_paths" /> </provider>
- 在
res/xml目录下新建file_paths.xml,配置允许对外暴露的目录:
<?xml version="1.0" encoding="utf-8"?> <paths xmlns:android="http://schemas.android.com/apk/res/android"> <!-- 匹配你示例中的私有files下的子目录 --> <files-path name="internal_docs" path="files/default/documents/" /> </paths>
- 代码中生成content URI
- Kotlin示例:
val targetFile = File("/data/user/0/com.nativetemplate/files/files/default/documents/3377699720528075@1634821435640") val contentUri = FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", targetFile)- Java示例:
File targetFile = new File("/data/user/0/com.nativetemplate/files/files/default/documents/3377699720528075@1634821435640"); Uri contentUri = FileProvider.getUriForFile(context, context.getPackageName() + ".fileprovider", targetFile);
如果需要将URI分享给其他应用读写,需要临时授予访问权限:
// 授予目标应用读写权限 context.grantUriPermission("目标应用包名", contentUri, Intent.FLAG_GRANT_READ_URI_PERMISSION or Intent.FLAG_GRANT_WRITE_URI_PERMISSION)
方案2:直接将文件转为Base64
如果不需要和其他应用共享URI,仅需要文件内容编码,直接读取私有目录文件流即可,不需要额外申请权限:
- Kotlin示例:
val targetFile = File("/data/user/0/com.nativetemplate/files/files/default/documents/3377699720528075@1634821435640") val base64Content = targetFile.inputStream().use { input -> val byteArray = input.readBytes() Base64.encodeToString(byteArray, Base64.DEFAULT) }
- Java示例:
File targetFile = new File("/data/user/0/com.nativetemplate/files/files/default/documents/3377699720528075@1634821435640"); FileInputStream fis = new FileInputStream(targetFile); byte[] byteArray = new byte[(int) targetFile.length()]; fis.read(byteArray); fis.close(); String base64Content = Base64.encodeToString(byteArray, Base64.DEFAULT);
注意:该方案仅适用于小文件,大文件直接读取全量字节会触发OOM,建议优先用方案1处理。
补充说明
如果你的路径属于其他应用的私有目录,无ROOT权限或对应应用的ContentProvider授权的情况下无法访问,上述方案仅适用于你自己应用私有目录下的文件。
内容的提问来源于stack exchange,提问作者Elvisworld
相关产品推荐
相关产品推荐

