鸿蒙HarmonyOS之选择相册文件(照片/视频)方法

一、新建文件工具类FileUtil.ets

包含:选择照片方法、获取文件类型方法、去除后缀、获取后缀方法

复制代码
import { BusinessError, request } from '@kit.BasicServicesKit';
import photoAccessHelper from '@ohos.file.photoAccessHelper';
import bundleManager from '@ohos.bundle.bundleManager';

/**
 * 选择图库图片
 * @param selectMax 选择文件数量限制
 * @param selectType 选择文件类型限制
 * @returns
 */
export async function fileSelect(selectMax: number,selectType: photoAccessHelper.PhotoViewMIMETypes): Promise<Array<string>> {
  try {
    // //选择图片的类型
    // let recommendOptions: photoAccessHelper.RecommendationOptions = {
    //   recommendationType: photoAccessHelper.RecommendationType.ID_CARD
    // }
    let options: photoAccessHelper.PhotoSelectOptions = {
      MIMEType: selectType,
      maxSelectNumber: selectMax,
      // recommendationOptions: recommendOptions
    }
    let photoPicker = new photoAccessHelper.PhotoViewPicker();

    // 使用 await 确保异步操作完成
    const PhotoSelectResult = await photoPicker.select(options);

    // 成功获取结果后返回字符串形式的结果
    console.info('PhotoViewPicker.select successfully, result is: ' + JSON.stringify(PhotoSelectResult));
    if (PhotoSelectResult && PhotoSelectResult.photoUris && PhotoSelectResult.photoUris.length > 0) {
      return PhotoSelectResult.photoUris;
    }else{
      return [];
    }
  } catch (error) {
    // 处理捕获到的错误,并返回空
    let err: BusinessError = error as BusinessError;
    console.error(`PhotoViewPicker failed with err: ${err.code}, ${err.message}`);
    return []; // 返回空
  }
}


/**
 * 获取文件类型
 * @param uri
 * @returns
 */
export function getFileTypeFromExtension(uri: string): 'image' | 'video' | 'unknown' {
  const fileName = uri.substring(uri.lastIndexOf('/') + 1);
  const fileExtension = fileName.split('.').pop()?.toLowerCase();

  if (fileExtension) {
    switch (fileExtension) {
      case 'jpg':
      case 'jpeg':
      case 'png':
      case 'bmp':
      case 'gif':
        return 'image';
      case 'mp4':
      case 'avi':
      case 'mov':
      case 'mkv':
        return 'video';
      default:
        return 'unknown';
    }
  }

  return 'unknown';
}

/**
 * 去除后缀的文件名
 * @param uri
 * @returns
 */
export function removeFileExtension(uri: string): string {
  const fileName = uri.substring(uri.lastIndexOf('/') + 1);
  const baseName = fileName.split('.').slice(0, -1).join('.');
  return uri.replace(fileName, baseName);
}

/**
 * 获取后缀
 * @param uri
 * @returns
 */
export function getFileExtensionWithDot(uri: string): string {
  const lastDotIndex = uri.lastIndexOf('.');
  if (lastDotIndex > -1) {
    return uri.substring(lastDotIndex);
  }
  return ''; // 如果没有找到后缀名,则返回空字符串
}

二、使用示例

1、选择一张图片文件

复制代码
fileSelect(1, photoAccessHelper.PhotoViewMIMETypes.IMAGE_VIDEO_TYPE).then((uriArray: Array<string>) => {
          if (uriArray && uriArray.length > 0) {
            this.imageUri = uriArray[0];
            Logger.debug(this.TAG,'选择的图片Uri是:'+ this.imageUri)
          }else{
            Logger.debug(this.TAG,'未选择图片!')
            showToast('未选择图片!')
          }
        });

2、选择多个文件,不限图片或视频

复制代码
fileSelect(20, photoAccessHelper.PhotoViewMIMETypes.IMAGE_VIDEO_TYPE)
        .then((uriArray: Array<string>) => {
          if (uriArray && uriArray.length > 0) {
            Logger.debug(this.TAG, '准备上传')
            for (let index = 0; index < uriArray.length; index++) {
              const itemUri = uriArray[index];
              let type: string = getFileTypeFromExtension(itemUri);
              let suffix: string = getFileExtensionWithDot(itemUri);
              Logger.debug(this.TAG, '选择照片的uri = ' + itemUri)
              Logger.debug(this.TAG, '文件类型是:' + type + ', 文件后缀是:' + suffix);
              //......
            }
          } else {
            Logger.debug(this.TAG, '未选择文件!')
            showToast('未选择文件!')
          }
        })

三、完成,Nice!

相关推荐
OH_TPC1 小时前
【鸿蒙优选三方库】@ohos/mpchart:让 HarmonyOS 应用的数据可视化开箱即用
华为·信息可视化·harmonyos·鸿蒙
轻口味6 小时前
端侧 AI 赋能鸿蒙版 Obsidian:轻规划基于 HarmonyOS 7.0 图像超分特性的体验突破与开发实战
人工智能·华为·harmonyos·鸿蒙
OH_TPC8 小时前
【鸿蒙优选三方库】@ohos/lottie:让 After Effects 动画在 HarmonyOS 上稳定播放
华为·harmonyos·鸿蒙
2501_9197490310 小时前
华为鸿蒙训练口才APP—小羊口才
华为·harmonyos·鸿蒙
woshihuanglaoshi12 小时前
鸿蒙老旧项目升级改造高级:API废弃迁移/ArkTS语法升级/架构重构策略/增量迁移/风险管控方案
学习·华为·重构·架构·harmonyos·鸿蒙
M-Robots echo1 天前
王成录:分布式软总线是 M-Robots 实现群体智能的技术内核
机器人·ros·鸿蒙·开源社区·m-robots
OH_TPC1 天前
【鸿蒙优选三方库】@ohos/ijkplayer:在鸿蒙上像 B 站一样流畅播视频
华为·音视频·harmonyos·鸿蒙
2501_919749032 天前
华为鸿蒙经期记录APP—小羊月经
华为·harmonyos·鸿蒙
黑鲨吃西瓜2 天前
鸿蒙通用模块
harmonyos·鸿蒙
math_hongfan3 天前
鸿蒙离线数据缓存高级架构:弱网预加载/离线数据优先级/同步冲突解决/上线后数据合并策略
学习·缓存·华为·架构·harmonyos·鸿蒙