鸿蒙分享(六):文件视频图片选择+保存到相册

server/2024/12/14 15:19:00/

代码仓库:https://gitee.com/linguanzhong/share_harmonyos 鸿蒙api:12

引用的harmony-utils地址:OpenHarmony三方库中心仓

1.拷贝文件到缓存目录

import { FileUtil, ObjectUtil } from '@pura/harmony-utils'
import { common } from '@kit.AbilityKit'
import { BusinessError } from '@kit.BasicServicesKit'
import { BaseDialog } from './dialog/BaseDialog'
import fs from '@ohos.file.fs'//拷贝文件到缓存目录
static copyFileToCache(mkdir: string, originPath: string, success: (cachePath: string, originalPath?: string) => void,fail: (err: BusinessError) => void,isShowLoading: boolean = true) {if (isShowLoading) {BaseDialog.showLoading()}fs.open(originPath, fs.OpenMode.READ_ONLY).then((file: fs.File) => {let path = FileUtil.getCacheDirPath(mkdir) + '/' + file.namelet aaa = fs.accessSync(path)if (aaa) {if (isShowLoading) {BaseDialog.hintLoading()}success(path, originPath)fs.closeSync(file);} else {fs.copyFile(file.fd, path).then(() => {if (isShowLoading) {BaseDialog.hintLoading()}success(path, originPath)fs.closeSync(file);}).catch((err: BusinessError) => {if (isShowLoading) {BaseDialog.hintLoading()}fail(err)})}}).catch((err: BusinessError) => {if (isShowLoading) {BaseDialog.hintLoading()}fail(err)})
}

文件选择

//文件选择
static setFilePicker(context: Context,documentSelectOptions: picker.DocumentSelectOptions,successCallBack: (uris: Array<string>) => void,errorCallBack: (err: BusinessError) => void) {const documentViewPicker = new picker.DocumentViewPicker(context);documentViewPicker.select(documentSelectOptions).then((documentSelectResult: Array<string>) => {successCallBack(documentSelectResult)}).catch((err: BusinessError) => {errorCallBack(err)})
}

使用:

BaseText({text: "文件选择",fontColor: $r('app.color.color_DD2942')
}).margin({top: 10
}).onClick(() => {let options = new picker.DocumentSelectOptions()options.maxSelectNumber = 1options.authMode = trueBaseUtil.setFilePicker(getContext(), options, (uris) => {BaseLog.i("uris:" + uris.toString())if (uris.length > 0) {uris.forEach(item => {BaseUtil.copyFileToCache("file", item, (path) => {BaseLog.i("path:" + path) //  /data/storage/el2/base/haps/entry/cache/file/欢迎使用华为文件管理.pdf}, (error) => {BaseLog.i("error11:" + JSON.stringify(error))})})}}, (error) => {BaseDialog.showToast("调用文件选择失败:" + error.message)})
})

图片或视频选择

申请权限:

"requestPermissions": [{"name": "ohos.permission.READ_IMAGEVIDEO","reason": "$string:permission_READ_IMAGEVIDEO","usedScene": {"abilities": []}},{"name": "ohos.permission.WRITE_IMAGEVIDEO","reason": "$string:permission_READ_IMAGEVIDEO","usedScene": {"abilities": []}}
]

申请权限之后登录签名

//type:0图片 1:视频
getPermission(type: number) {let ps: Permissions[] = ['ohos.permission.READ_IMAGEVIDEO'];PermissionUtil.requestPermissions(ps).then((result) => {if (result) {this.photoSelect(type)} else {BaseDialog.showToast("权限申请失败")}})
}//type:0图片 1:视频photoSelect(type: number) {let options: photoAccessHelper.PhotoSelectOptions = {isEditSupported: true,isOriginalSupported: true,maxSelectNumber: type == 0 ? 1 : 1,isSearchSupported: true,MIMEType: type == 0 ? photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE : photoAccessHelper.PhotoViewMIMETypes.VIDEO_TYPE}PhotoHelper.select(options).then((uris: string[]) => {if (uris.length > 0) {uris.forEach(item => {BaseUtil.copyFileToCache("image", item, (path) => {if (type == 0) {if (FileUtil.lstatSync(path).size >= 5 * 1024 * 1024) {BaseDialog.showToast("只能上传大小为5M以下的图片~")} else {}} else {if (FileUtil.lstatSync(path).size >= 20 * 1024 * 1024) {BaseDialog.showToast("只能上传大小为20M以下的视频~")} else {}}}, (error) => {})})}}).catch((err: BusinessError) => {BaseDialog.showToast("调用相册失败:" + err.message)})}

使用:

BaseText({text: "视频选择",fontColor: $r('app.color.color_DD2942')
}).margin({top: 10
}).onClick(() => {this.getPermission(0)
})

保存到相册

  //保存到相册static async save(filePath: string, fileName: string, success: (path: string) => void, fail: (err: BusinessError) => void) {BaseDialog.showLoading()let photoHelper = photoAccessHelper.getPhotoAccessHelper(getContext());let uri = fileUri.getUriFromPath(filePath)let assetChangeRequest: photoAccessHelper.MediaAssetChangeRequest =photoAccessHelper.MediaAssetChangeRequest.createImageAssetRequest(getContext(), uri);photoHelper.applyChanges(assetChangeRequest).then((s) => {BaseDialog.hintLoading()success(filePath)BaseDialog.hintLoading()}).catch((err: BusinessError) => {fail(err)BaseDialog.hintLoading()})}//拷贝到图库static saveToAlbum(downLoadUrl: string, success: (path: string) => void, fail: (err: BusinessError) => void) {let e: BusinessError = {code: 0,name: '',message: ''}PermissionUtil.requestPermissions('ohos.permission.WRITE_IMAGEVIDEO').then((result) => {if (result) {let filePath = ""let fileName = ""let aa = downLoadUrl.split("/")if (aa.length != 0) {fileName = aa[aa.length-1]//有些图片链接不是.jpg结尾if (fileName.indexOf(".") == -1) {fileName += ".jpg"}BaseLog.i("fileName:" + fileName)filePath = BaseUtil.getImagePathByFileName(fileName)}BaseLog.i("filePath:" + filePath)if (BaseUtil.isEmpty(filePath)) {filePath = BaseUtil.getImagePath() + '/' + fileNamelet baseRequestSet = new BaseRequestSet()baseRequestSet.url = downLoadUrlbaseRequestSet.filePath = filePathbaseRequestSet.isLoading = truenew BaseHttp().downloadFile(baseRequestSet,(msg) => {BaseUtil.save(msg ?? "", fileName, success, fail)},(error) => {e.message = error.messagee.code = Number(error.code)fail(e)},() => {},(progress) => {BaseLog.i("progress:" + progress.progress)})} else {BaseUtil.save(filePath, fileName, success, fail)}} else {e.message = "权限申请失败"fail(e)}})}

使用:

BaseText({text: "下载保存到图库",fontColor: $r('app.color.color_DD2942')
}).margin({top: 10
}).onClick(() => {BaseUtil.saveToAlbum("https://pics4.baidu.com/feed/314e251f95cad1c8dd6c162f5b8c5b07c83d5127.jpeg", (success) => {BaseDialog.showToast("保存成功:" + success)}, (error) => {BaseDialog.showToast(error.message)})
})

http://www.ppmy.cn/server/150123.html

相关文章

【组件介绍】FITKPlotWindow

一、组件简介 二维图表组件FITKPlotWindow基于Qwt开发&#xff0c;是用于直观二维数据的组件。目前的二维图表组件支持四种类型的图表&#xff0c;分别为标准直角坐标图、柱状图、频谱图和极坐标图。该组件的数据渲染效果示例如下&#xff1a; 二、主要接口 组件中针对不同的…

JavaCV之FFmpegFrameFilter视频转灰度

1、代码 package com.example.demo.ffpemg;import lombok.SneakyThrows; import org.bytedeco.javacv.*;public class FFmpegFrameFilterVideoExample {SneakyThrowspublic static void main(String[] args) {// 输入视频文件路径String inputVideoPath "f:/2222.mp4&qu…

51c大模型~合集89

我自己的原文哦~ https://blog.51cto.com/whaosoft/12815167 #OpenAI很会营销 而号称超强AI营销的灵感岛实测成效如何&#xff1f; OpenAI 是懂营销的&#xff0c;连续 12 天发布&#xff0c;每天一个新花样&#xff0c;如今刚过一半&#xff0c;热度依旧不减。 毫无疑问&…

【Spring】日志类Logger的使用

在Spring框架中&#xff0c;日志记录是一个重要的组成部分&#xff0c;通常使用不同的日志框架来处理应用程序的日志。Spring 本身并直接提供一个名为Logger 的类&#xff0c;而是通过抽象的日志 API 让开发者能够选择和使用不同的日志实现&#xff08;如 Log4j、Logback、SLF4…

力扣1049.最后一块石头的重量(01背包)之理解篇

1049. 最后一块石头的重量 II class Solution { public:int lastStoneWeightII(vector<int>& stones) {int sumNum 0;for(int i 0;i < stones.size();i){sumNum stones[i];}int target sumNum / 2;vector<int>dp(target 1, 0);for(int i 0;i < st…

后端接受前端传递数组进行批量删除

问题描述&#xff1a;当我们需要做批量删除功能的时候&#xff0c;我们循环单次删除的接口也能进行批量删除&#xff0c;但要删除100条数据就要调用100次接口&#xff0c;或者执行100次sql&#xff0c;这样系统开销是比较大的&#xff0c;那么我们直接采用接收的数组格式数据sq…

springboot423玩具租赁系统boot(论文+源码)_kaic

摘 要 传统办法管理信息首先需要花费的时间比较多&#xff0c;其次数据出错率比较高&#xff0c;而且对错误的数据进行更改也比较困难&#xff0c;最后&#xff0c;检索数据费事费力。因此&#xff0c;在计算机上安装玩具租赁系统软件来发挥其高效地信息处理的作用&#xff0c…

OpenAI 正式赋予 ChatGPT 通过视频实时与用户互动的能力

每周跟踪AI热点新闻动向和震撼发展 想要探索生成式人工智能的前沿进展吗&#xff1f;订阅我们的简报&#xff0c;深入解析最新的技术突破、实际应用案例和未来的趋势。与全球数同行一同&#xff0c;从行业内部的深度分析和实用指南中受益。不要错过这个机会&#xff0c;成为AI领…