📌 场景介绍

文档类应用经常涉及以下操作:

  • 让用户选择本地文件

  • 识别并打开 PDF、Excel、Word、TXT 等文件

  • 调用系统默认查看器或第三方 App 打开文件

本篇实现:

  • 调用系统文件选择器

  • 选择任意类型的文件(支持格式筛选)

  • 获取文件路径并提示用户

  • 可拓展为跳转默认打开方式


🧱 页面结构

/entry/src/main/ets
  └── pages/
       └── FileOpenDemo.ets     // 文件选择并打开页面

🧱 权限配置(config.json)

"reqPermissions": [
  { "name": "ohos.permission.READ_USER_STORAGE" }
]

🧩 FileOpenDemo.ets 示例页面

import picker from '@ohos.file.picker'
import wantAgent from '@ohos.wantAgent'

@Entry
@Component
struct FileOpenDemo {
  @State filePath: string = ''
  @State status: string = '尚未选择文件'

  private async openFilePicker() {
    const filePicker = new picker.FilePicker()
    filePicker.suffixFilter = ['pdf', 'xlsx', 'xls', 'docx', 'txt']

    try {
      const uris = await filePicker.show()
      if (uris.length === 0) {
        this.status = '❌ 未选择任何文件'
        return
      }

      this.filePath = uris[0]
      this.status = '✅ 已选择文件:' + this.filePath
    } catch (err) {
      console.error('文件选择失败:', JSON.stringify(err))
      this.status = '❌ 选择失败'
    }
  }

  private async openFileWithSystem() {
    if (!this.filePath) {
      this.status = '⚠️ 请先选择文件'
      return
    }

    try {
      const wantAgentInfo = {
        wants: [{
          action: 'ohos.intent.action.VIEW',
          uri: this.filePath,
          type: '', // 可填写 MIME 类型,如 application/pdf
        }],
        operationType: wantAgent.OperationType.START_ABILITY,
        requestCode: 0,
      }

      const agent = await wantAgent.getWantAgent(wantAgentInfo)
      await wantAgent.triggerWantAgent(agent)
      this.status = '📂 打开请求已发送'
    } catch (err) {
      console.error('打开失败:', JSON.stringify(err))
      this.status = '❌ 无法打开该文件'
    }
  }

  build() {
    Column() {
      Text("📁 文件选择并打开").fontSize(22).margin(20)

      Button("选择文件").onClick(() => this.openFilePicker()).margin(10)
      Button("使用系统打开").onClick(() => this.openFileWithSystem()).margin(10)

      Text(this.status).fontSize(14).fontColor('#555').margin(20)
    }
    .padding(30)
    .height('100%')
  }
}

✅ 效果说明

  • 支持筛选并选择 PDF、Excel、Word、TXT 等文件

  • 显示用户选中的文件路径

  • 调用系统能力打开该文件(若有支持的 App)


🔧 拓展建议

  • 匹配 MIME 类型细分打开方式(如 application/pdf

  • 添加 MIME 检测和格式判断(防止异常)

  • 支持调用自定义文件预览组件或第三方插件预览

Logo

讨论HarmonyOS开发技术,专注于API与组件、DevEco Studio、测试、元服务和应用上架分发等。

更多推荐