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

代码仓库: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.name
    let 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 = 1
  options.authMode = true
  BaseUtil.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() + '/' + fileName
          let baseRequestSet = new BaseRequestSet()
          baseRequestSet.url = downLoadUrl
          baseRequestSet.filePath = filePath
          baseRequestSet.isLoading = true
          new BaseHttp().downloadFile(baseRequestSet,
            (msg) => {
              BaseUtil.save(msg ?? "", fileName, success, fail)
            },
            (error) => {
              e.message = error.message
              e.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)
  })
})
相关推荐
万物智能信息科技9 小时前
温湿度传感器驱动开发—【万物智能之开源鸿蒙OpenHarmony系统实战开发系列教程】
人工智能·驱动开发·华为·开源·harmonyos·鸿蒙
熊猫钓鱼>_>12 小时前
Kotlin Multiplatform for OpenHarmony 实战:为 Landscapist 实现图片加载适配
开发语言·kotlin·华为云·ai编程·harmonyos·鸿蒙·openharmony
m0_7381858212 小时前
Flutter 鸿蒙化实战:qr_code_scanner_plus 适配 OpenHarmony,二维码扫描
flutter·华为·harmonyos·鸿蒙
2501_919749032 天前
华为鸿蒙免费记账与生活统计APP—小羊统计
华为·生活·harmonyos·鸿蒙
m0_738185822 天前
Flutter 鸿蒙化实战:qrcode_flutter 适配 OpenHarmony,二维码生成与识别
数码相机·flutter·华为·harmonyos·鸿蒙
万物智能信息科技2 天前
血氧心跳传感器MAX30100芯片驱动开发—【万物智能之开源鸿蒙OpenHarmony系统实战开发系列教程】
人工智能·驱动开发·华为·开源·harmonyos·鸿蒙
老陈说编程2 天前
1. 鸿蒙 (HarmonyOS) 2012 至 2026 年的发展历程
分布式·华为·个人开发·harmonyos·鸿蒙·鸿蒙系统·程序员创富
m0_738185822 天前
Flutter 鸿蒙化实战:open_app_settings 适配 OpenHarmony,一键跳转系统设置
flutter·华为·harmonyos·鸿蒙
m0_738185822 天前
Flutter 鸿蒙化实战:qr_code_scanner 适配 OpenHarmony,相机扫码实时识别
数码相机·flutter·华为·harmonyos·鸿蒙
MardaWang2 天前
当滚动逃离了框架 ——HarmonyOS Web 与原生混排滚动的冲突本质与解法
harmonyos·arkts·鸿蒙·deveco studio