You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在React Native中用react-native-file-viewer打开本地文件报错如何解决

问题定位

你的代码存在两处核心逻辑错误,是导致报错的直接原因:

  • RNFS.copyFileAssets入参顺序完全颠倒,该方法参数顺序为(源文件路径, 目标存储路径),你把源和目标写反了
  • 路径拼接逻辑错误:initPath是RNFS.DownloadDirectoryPath目录路径,你直接把它拼到目标路径中,还试图将目录作为单文件拷贝、打开,自然找不到对应pdf文件

修复方案

1. 修正文件打开逻辑

你报错中显示的pdf文件本身已经存放在应用私有文档目录下,不需要额外拷贝到下载目录,直接调用打开方法即可:

// 替换为你实际的动态文件路径变量
const targetFile = `${RNFS.DocumentDirectoryPath}/JharkhandUpdate/JharkhandUpdateDocuments/1621524753737_JharkhandUpdate_Madhushree%20Das_47.pdf`;

// 先确认文件是否存在,排查文件丢失问题
const fileExists = await RNFS.exists(targetFile);
if (!fileExists) {
  console.log("目标文件不存在,请检查下载/存储逻辑");
  return;
}

FileViewer.open(targetFile, {
  // 安卓端可选开启,唤起应用选择列表
  showOpenWithDialog: true
})
.then(() => console.log("文件打开成功"))
.catch(err => console.log("打开失败", err));

如果你确实需要先拷贝到公共下载目录再打开,修正拷贝逻辑:

const sourcePath = `${RNFS.DocumentDirectoryPath}/JharkhandUpdate/JharkhandUpdateDocuments/1621524753737_JharkhandUpdate_Madhushree%20Das_47.pdf`;
const destPath = `${RNFS.DownloadDirectoryPath}/1621524753737_JharkhandUpdate_Madhushree Das_47.pdf`;

RNFS.copyFile(sourcePath, destPath)
.then(() => FileViewer.open(destPath, { showOpenWithDialog: true }))
.then(() => console.log("操作完成"))
.catch(err => console.log(err));

2. 检查安卓端配置

  • 权限配置:在AndroidManifest.xml中添加对应权限,安卓13及以上添加READ_MEDIA_*系列对应文件类型权限,低版本添加READ_EXTERNAL_STORAGE、WRITE_EXTERNAL_STORAGE
  • FileProvider配置:安卓7及以上必须配置FileProvider才能让第三方应用访问你的应用内文件,在AndroidManifest.xml的application节点下添加:
<provider
  android:name="androidx.core.content.FileProvider"
  android:authorities="${applicationId}.fileprovider"
  android:grantUriPermissions="true"
  android:exported="false">
  <meta-data
    android:name="android.support.FILE_PROVIDER_PATHS"
    android:resource="@xml/filepaths" />
</provider>

在res/xml目录下新建filepaths.xml,内容如下:

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
  <files-path name="app_files" path="." />
  <external-files-path name="external_app_files" path="." />
  <external-path name="public_storage" path="." />
</paths>

3. 额外排查项

  • 确认设备上已经安装了对应格式的打开应用,比如打开pdf需要设备上有pdf阅读器
  • 路径中的%20是空格的标准URL编码,不需要手动替换,库内部会自动处理

内容的提问来源于stack exchange,提问作者Md Javed Akhtar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 15:54:03