鸿蒙应用开发之鸿蒙沙箱文件如何存媒体库?

效果展示

实现思路

完整代码

typescript 复制代码
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { fileIo } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { promptAction } from '@kit.ArkUI';
import { BusinessError, request } from '@kit.BasicServicesKit';
import { image } from '@kit.ImageKit';

async function savePhotoToGallery(context: common.UIAbilityContext, url:string) {
  let helper = photoAccessHelper.getPhotoAccessHelper(context);
  try {
    // onClick触发后10秒内通过createAsset接口创建图片文件,10秒后createAsset权限收回。
    let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg');
    // 使用uri打开文件,可以持续写入内容,写入过程不受时间限制
    let file = await fileIo.open(uri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
    // 写到媒体库文件中
    const source = image.createImageSource(url) // 图片对象
    const packer = image.createImagePacker() // 创建打包对象
    const buffer = await packer.packing(source, {
      quality: 100,
      format: 'image/jpeg'
    })
    await fileIo.write(file.fd, buffer);
    await fileIo.close(file.fd);
    promptAction.showToast({ message: '已保存至相册!' });
  }
  catch (error) {
    const err: BusinessError = error as BusinessError;
    console.error(`Failed to save photo. Code is ${err.code}, message is ${err.message}`);
  }
}

@Entry
@Component
struct Index {
  build() {
    Row() {
      Column({ space: 10 }) {
        // $r('app.media.startIcon')需要替换为开发者所需的图像资源文件
        Image('http://tmp00002.zhaodashen.cn/jd.png').width('100%')


        SaveButton()
          .padding({top: 12, bottom: 12, left: 24, right: 24})
          .onClick(async (event: ClickEvent, result: SaveButtonOnClickResult) => {
            if (result === SaveButtonOnClickResult.SUCCESS) {
              const context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
              // 免去权限申请和权限请求等环节,获得临时授权,保存对应图片
              // =======================
              try {
                // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
                request.downloadFile(
                  getContext(),
                  {
                    url: 'http://tmp00002.zhaodashen.cn/jd.png',
                    filePath: context.filesDir + '/hello3.jpg'
                  }
                ).then((data: request.DownloadTask) => {
                  let downloadTask: request.DownloadTask = data;

                  downloadTask.on('progress', (receivedSize: number, totalSize: number) => {
                    console.log('下载中:', receivedSize, totalSize)
                  })

                  downloadTask.on('complete', () => {
                    console.log('下载完成') // 保存到媒体库中✅
                    savePhotoToGallery(context, context.filesDir + '/hello3.jpg');
                  })
                }).catch((err: BusinessError) => {
                  console.error(`Failed to request the download. Code: ${err.code}, message: ${err.message}`);
                })
              } catch (err) {
                console.error(`Failed to request the download. err: ${JSON.stringify(err)}`);
              }
              // =======================
            } else {
              promptAction.showToast({ message: '设置权限失败!' })
            }
          })
      }
      .width('100%')
    }
    .height('100%')
    .backgroundColor(0xF1F3F5)
  }
}

鸿蒙开发者班级

相关推荐
OH_TPC12 小时前
【鸿蒙优选三方库】@ohos/mpchart:让 HarmonyOS 应用的数据可视化开箱即用
华为·信息可视化·harmonyos·鸿蒙
woshihuanglaoshi16 小时前
鸿蒙技术进阶全景高级成长体系:从初中级到架构师的技能树/学习路径/项目实战/认证体系系统性方法论
学习·华为·harmonyos
轻口味17 小时前
端侧 AI 赋能鸿蒙版 Obsidian:轻规划基于 HarmonyOS 7.0 图像超分特性的体验突破与开发实战
人工智能·华为·harmonyos·鸿蒙
OH_TPC19 小时前
【鸿蒙优选三方库】@ohos/lottie:让 After Effects 动画在 HarmonyOS 上稳定播放
华为·harmonyos·鸿蒙
李蚊子20 小时前
鸿蒙应用开发实践与上架复盘
harmonyos
2501_9197490321 小时前
华为鸿蒙训练口才APP—小羊口才
华为·harmonyos·鸿蒙
大锅盖11 天前
HarmonyOS 摄像头焦点管理的完整工程实现
华为·harmonyos
woshihuanglaoshi1 天前
鸿蒙老旧项目升级改造高级:API废弃迁移/ArkTS语法升级/架构重构策略/增量迁移/风险管控方案
学习·华为·重构·架构·harmonyos·鸿蒙
星空真迷人2 天前
嵌入式鸿蒙并非精简版,核心究竟是什么?
stm32·单片机·嵌入式硬件·物联网·华为·harmonyos·iot
OH_TPC2 天前
【鸿蒙优选三方库】@ohos/ijkplayer:在鸿蒙上像 B 站一样流畅播视频
华为·音视频·harmonyos·鸿蒙