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

如何在Apache Cordova移动应用中使用@capacitor-community/file-opener?

@capacitor-community/file-opener 使用示例

1. 安装依赖

npm install @capacitor-community/file-opener
npx cap sync

2. 基础使用示例(打开设备本地文件)

先导入库,再调用打开方法:

import { FileOpener } from '@capacitor-community/file-opener';

// 打开本地PDF文件示例
async function openLocalPDF() {
  try {
    await FileOpener.open({
      filePath: '/storage/emulated/0/Download/sample.pdf', // Android路径示例,iOS需替换为对应可访问路径
      contentType: 'application/pdf' // 对应文件的MIME类型
    });
    console.log('文件已成功打开');
  } catch (error) {
    console.error('打开文件失败:', error);
  }
}

3. 打开Assets目录中的文件

由于库无法直接访问Assets目录文件,需先复制到应用可读写目录再打开:

import { FileOpener } from '@capacitor-community/file-opener';
import { Filesystem, Directory } from '@capacitor/filesystem';

async function openAssetGuide() {
  try {
    // 读取Assets中的文件
    const assetFile = await Filesystem.readFile({
      path: 'assets/guides/user-manual.pdf',
      directory: Directory.Assets
    });

    // 将文件写入应用缓存目录
    const cachedFile = await Filesystem.writeFile({
      path: 'user-manual.pdf',
      data: assetFile.data,
      directory: Directory.Cache
    });

    // 打开缓存目录中的文件
    await FileOpener.open({
      filePath: cachedFile.uri,
      contentType: 'application/pdf'
    });
  } catch (error) {
    console.error('操作失败:', error);
  }
}

4. 错误处理优化示例

针对性捕获常见错误场景:

async function openFileWithErrorHandle() {
  try {
    await FileOpener.open({
      filePath: '/storage/emulated/0/Download/non-exist.docx',
      contentType: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
    });
  } catch (error: any) {
    if (error.message.includes('File not found')) {
      console.error('指定文件不存在,请检查路径');
    } else if (error.message.includes('No app available')) {
      console.error('设备未安装支持该文件类型的应用');
    } else {
      console.error('未知错误:', error);
    }
  }
}

关键说明

  • contentType 必须匹配文件的MIME类型,比如图片用image/jpeg、文本用text/plain
  • Android访问公共存储目录时,需提前申请READ_EXTERNAL_STORAGE权限
  • iOS仅允许访问应用沙箱内的文件(如Documents、Cache目录)

内容的提问来源于stack exchange,提问作者XxHaRuToxX

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 12:23:13