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

​

​

效果展示

实现思路

完整代码

​

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_TPC1 天前
HarmonyOS APP开发---“动效君“UI动效素材库App,需要用到这个库
ui·华为·harmonyos·鸿蒙
贾伟康1 天前
HarmonyOS 3DGS 滤镜切换实战:效果创建、参数管理与资源释放
harmonyos·arkts·鸿蒙开发·技术实践·空间化体验
HarmonyOS_SDK1 天前
【HarmonyOS API 26】分布式数字身份DID:系统级可信身份体系
harmonyos
贾伟康1 天前
HarmonyOS GSNode 场景控制实战:位置、缩放、可见性与状态同步
harmonyos·arkts·鸿蒙开发·技术实践·空间化体验
redtank20001 天前
纯血鸿蒙本地音乐播放器开发实战:我爱听歌架构解析
harmonyos
贾伟康1 天前
HarmonyOS API 26 分块 3DGS 实战:相机驱动、瓦片回调与并发去重
性能优化·harmonyos·arkts·3dgs·spatial recon kit
万物智能信息科技1 天前
指纹识别传感器驱动开发—【万物智能之开源鸿蒙OpenHarmony系统实战开发系列教程】
驱动开发·华为·开源·harmonyos·鸿蒙
贾伟康2 天前
【共创稿事节】HarmonyOS 7.0 AOT编译优化:从接入到生产验证
harmonyos·arkts·路由·navigation·navdestination
2601_949480062 天前
开源鸿蒙平台 CMP 三方库「shadcn」适配全流程
华为·开源·harmonyos
Liaiyang662 天前
空圈容错视角-HarmonyOS 7 架构体检:从被动容错到主动免疫的真伪验证与生态反推
操作系统·harmonyos·架构设计·ai-agent·端云协同·鸿蒙7·空圈容错