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

ops/2024/10/19 15:25:57/

一、新建文件工具类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!


http://www.ppmy.cn/ops/122078.html

相关文章

vite学习教程02、vite+vue2配置环境变量

文章目录 前言1、安装依赖2、配置环境变量3、应用环境变量4、运行和构建项目资料获取 前言 博主介绍&#xff1a;✌目前全网粉丝3W&#xff0c;csdn博客专家、Java领域优质创作者&#xff0c;博客之星、阿里云平台优质作者、专注于Java后端技术领域。 涵盖技术内容&#xff1…

Hive数仓操作(八)

一、Hive中的分桶表 1. 分桶表的概念 分桶表是Hive中一种用于提升查询效率的表类型。分桶指的是根据指定列的哈希值将数据划分到不同的文件&#xff08;桶&#xff09;中。 2. 分桶表的原理 哈希分桶&#xff1a;根据分桶列计算哈希值&#xff0c;对哈希值取模&#xff0c;将…

Kafka快速实战与基本原理详解

笔记:https://note.youdao.com/ynoteshare/index.html?id=b0357bdb4821ed2e35ecdbdacd65aa06&type=note&_time=1727570043631 启动kafka之前先启动zookper 看看ZK里面都有什么数据 : 刚开始什么数据都没有 接下来启动kafka,启动好后,日志在这里看: 启动好了kaf…

Linux的基本指令(1)

前提&#xff1a; a&#xff1a;博主是在云服务器上进行操作的 b&#xff1a;windows上普通文件在Linux中也叫作普通文件&#xff0c;但是windows上的文件夹&#xff0c;在Linux中叫作目录 c&#xff1a;文件 文件内容 文件属性(创建时间&#xff0c;修改时间&#xff0c;…

[Docker学习笔记]利用Dockerfile创建镜像

Dockerfile 指令 指令作用from继承基础镜像maintainer镜像制作者信息(可缺省)run用来执行shell命令expose暴露端口号cmd启动容器默认执行的命令entrypoint启动容器真正执行的命令volume创建挂载点env配置环境变量add复制文件到容器copy复制文件到容器workdir设置容器的工作目录…

基于大数据的二手房价数据可视化系统

作者&#xff1a;计算机学姐 开发技术&#xff1a;SpringBoot、SSM、Vue、MySQL、JSP、ElementUI、Python、小程序等&#xff0c;“文末源码”。 专栏推荐&#xff1a;前后端分离项目源码、SpringBoot项目源码、Vue项目源码、SSM项目源码、微信小程序源码 精品专栏&#xff1a;…

如何使用 Python 读取数据量庞大的 excel 文件

使用 pandas.read_excel 读取大文件时&#xff0c;的确会遇到性能瓶颈&#xff0c;特别是对于10万行20列这种规模的 .xlsx 文件&#xff0c;常规的 pandas 方法可能会比较慢。 要提高读取速度&#xff0c;关键是找到更高效的方式处理 Excel 文件&#xff0c;特别是在 Python 的…

[Day 82] 區塊鏈與人工智能的聯動應用:理論、技術與實踐

AI在風險控制中的應用案例 風險控制是企業管理中至關重要的一環&#xff0c;AI技術的引入為風險控制帶來了前所未有的自動化和智能化。無論是在金融、保險、製造業&#xff0c;還是網絡安全中&#xff0c;AI都能有效地分析和預測潛在風險。本文將探討AI在風險控制中的應用&…