鸿蒙NEXT上传图片功能PhotoViewPicker核心功能解析

鸿蒙NEXT上传图片功能PhotoViewPicker核心功能解析 #ArkTS#鸿蒙Next#HarmonyOS SDK应用服务#HarmonyOS 语言

PhotoViewPicker 是鸿蒙系统中用于媒体资源选择的核心组件,通过它可以便捷地实现图片、视频等媒体文件的选择功能。下面从基本用法、参数配置到高级应用进行全面解析:

一、PhotoViewPicker 基础用法

PhotoViewPicker 的使用流程主要分为三步:

  1. 创建实例
  2. 配置参数
  3. 启动选择器获取结果

以下是最基本的使用示例:

typescript 复制代码
import photoAccessHelper from "@ohos.photoAccess.photoAccessHelper";

async function pickImage() {
  try {
    // 1. 创建选择器实例
    const picker = photoAccessHelper.createPhotoViewPicker();

    // 2. 配置选择参数(此处使用默认配置)
    const options = {
      MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE, // 只选择图片
      maxSelectNumber: 1, // 最多选择张数
      isSearchSupported: true, // 显示搜索
      isPhotoTakingSupported: true, // 支持拍照
      recommendationOptions: true, // 智能推荐
      preselectedUris: true, // 预览文件
      isPreviewForSingleSelectionSupported: true, // 单选是否支持预览
    };

    // 3. 启动选择器并获取结果
    const selectedAssets = await picker.select(options);

    if (selectedAssets.photoUris.length) {
      // 处理选择的资源
      console.info("选择的资源:", selectedAssets.photoUris);
    }
  } catch (error) {
    console.error("选择图片失败:", error);
  }
}

二、关键参数详解

PhotoViewPicker 的参数配置非常灵活,可以根据需求定制选择器的行为:

typescript 复制代码
const options = {
  MIMEType: photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE, // 只选择图片
  maxSelectNumber: 1, // 最多选择张数
  isSearchSupported: true, // 显示搜索
  isPhotoTakingSupported: true, // 支持拍照
  recommendationOptions: true, // 智能推荐
  preselectedUris: true, // 预览文件
  isPreviewForSingleSelectionSupported: true, // 单选是否支持预览
};

三、MIMEType 参数深度解析

MIMEType 参数是 PhotoViewPicker 中非常强大的一个配置项,它允许你精确控制选择器中显示的文件类型:

typescript 复制代码
// 示例1:只允许选择JPEG和PNG图片
IMAGE_TYPE = 'image/*',
// 示例2:只允许选择视频文件
VIDEO_TYPE = 'video/*',
// 示例3:
MOVING_PHOTO_IMAGE_TYPE = 'image/movingPhoto'
// 示例4:允许所有
IMAGE_VIDEO_TYPE = '*/*',

四、处理选择结果

选择器返回的结果是一个 PhotoSelectResult 对象,包含以下关键属性:

typescript 复制代码
class PhotoSelectResult {
  /**
   * The uris for the selected files.
   *
   * @type { Array<string> }
   * @syscap SystemCapability.FileManagement.PhotoAccessHelper.Core
   * @since 10
   */
  /**
   * The uris for the selected files.
   *
   * @type { Array<string> }
   * @syscap SystemCapability.FileManagement.PhotoAccessHelper.Core
   * @atomicservice
   * @since 11
   */
  /**
   * The uris for the selected files.
   *
   * @type { Array<string> }
   * @syscap SystemCapability.FileManagement.PhotoAccessHelper.Core
   * @crossplatform
   * @atomicservice
   * @since 12
   */
  photoUris: Array<string>;
  /**
   * Original option.
   *
   * @type { boolean }
   * @syscap SystemCapability.FileManagement.PhotoAccessHelper.Core
   * @since 10
   */
  /**
   * Original option.
   *
   * @type { boolean }
   * @syscap SystemCapability.FileManagement.PhotoAccessHelper.Core
   * @atomicservice
   * @since 11
   */
  /**
   * Original option.
   *
   * @type { boolean }
   * @syscap SystemCapability.FileManagement.PhotoAccessHelper.Core
   * @crossplatform
   * @atomicservice
   * @since 12
   */
  isOriginalPhoto: boolean;
}
  • 获取到资源后,通常需要进行以下处理:
  1. 使用文件 URI 读取文件内容
  2. 进行必要的格式转换(如压缩图片)
  3. 上传到服务器或保存到本地
ts 复制代码
// 这里以oss上传为例
// uri为选择图片路径
import { http } from '@kit.NetworkKit';
import fs from '@ohos.file.fs'
import { request } from '@kit.BasicServicesKit';
export async function upload (uri: string): Promise<string> {
  // 此处从服务器获取
  const data = {
    policy: 'qweqwe',
    signature: 'qweqwe',
    ossAccessKeyId: 'qweqwe',
    host: 'https://???/api',
  };
  const name = Date.now() + '.' + uri.split('.').pop();
  const key = `${new Date().getFullYear()}/${name}`
  const context = getContext();
  // 通过getContext获取沙箱地址
  const destPath = `${context.cacheDir}/${name}`;
  const file = fs.openSync(uri);
  // 将文件复制一份到沙箱缓存地址,这一步尤为重要,只有沙箱地址的文件可以进行上传操作
  fs.copyFileSync(file.fd, destPath);
  const result = await request.uploadFile(context,{
    // files字段是上传的文件组成的列表,类型为formData
    files: [{ filename: 'file', name: 'file', uri: `internal://cache/${name}`, type: 'image/jpeg' }],
    // data字段是携带的参数,建议把类型设置为formData
    data: [
      { name: 'name', value: `${name}`, },
      { name: 'policy', value: `${data.policy}` },
      { name: 'OSSAccessKeyId', value: Object.values(data)[2] },
      { name: 'signature', value: `${data.signature}` },
      { name: 'key', value: key },
    ],
    method: http.RequestMethod.POST,
    header: {
      Accept: '*/*',
      // 设置header确保参数类型为FormData
      "Content-Type": "multipart/form-data"
    },
    // 请求地址
    url: data.host
  });
  return new Promise((res, rej) => {
    result.on('progress', (u, t) => {
      console.log('进度', u / t);
    });
    result.on('complete', e => {
      console.log('ok', JSON.stringify(e));
      res(`${data.host + key}`);
    });
    result.on('fail', e => {
      console.log('错误', JSON.stringify(e));
      rej(e);
    })
  });
}

五、注意事项与常见问题

  • 权限要求 需要在 config.json 中声明文件访问权限:
json 复制代码
{
  "requestPermissions": [
    {
      "name": "ohos.permission.READ_MEDIA",
      "reason": "需要访问媒体文件"
    }
  ]
}
  • 文件处理注意

    • 系统媒体库中的文件 URI 通常是临时的,建议复制到应用私有目录再使用
ts 复制代码
const name = Date.now() + "";
const key = `${new Date().toLocaleDateString()}/${name}`;
const context = getContext();
const destPath = `${context.cacheDir}/${name}`;
const file = fileIo.openSync(uri);
fileIo.copyFileSync(file.fd, destPath);
console.log(destPath);
  • 大文件处理时建议进行异步操作,避免 UI 卡顿

  • request.uploadFile文件上传时候一直报错 401

  • 兼容性注意

      • 不同鸿蒙版本的 API 可能存在差异,建议在开发前查阅对应版本的官方文档
      • 部分参数(如 title、initialDirectory)可能只在特定版本中支持

通过合理配置 PhotoViewPicker 的各项参数,开发者可以轻松实现符合需求的媒体选择功能,为应用增色不少。

相关推荐
二流小码农14 分钟前
鸿蒙开发:实现一个标题栏吸顶
android·ios·harmonyos
坚果的博客40 分钟前
uniappx插件nutpi-idcard 开发与使用指南(适配鸿蒙)
华为·harmonyos
程序员小刘42 分钟前
【HarmonyOS 5】 社交行业详解以及 开发案例
华为·harmonyos
软件测试小仙女1 小时前
鸿蒙APP测试实战:从HDC命令到专项测试
大数据·软件测试·数据库·人工智能·测试工具·华为·harmonyos
Raink老师1 小时前
鸿蒙任务项设置案例实战
harmonyos·鸿蒙·案例实战
程序员小刘1 小时前
【HarmonyOS 5】 影视与直播详以及 开发案例
华为·harmonyos
程序员小刘1 小时前
鸿蒙【HarmonyOS 5】 (React Native)的实战教程
react native·华为·harmonyos
王二蛋与他的张大花2 小时前
HarmonyOS运动语音开发:如何让运动开始时的语音播报更温暖
harmonyos
Android研究员2 小时前
华为仓颉语言初识:并发编程之同步机制(上)
harmonyos
陈奕昆3 小时前
4.2 HarmonyOS NEXT分布式AI应用实践:联邦学习、跨设备协作与个性化推荐实战
人工智能·分布式·harmonyos