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

效果展示

实现思路

完整代码

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)
  }
}

鸿蒙开发者班级

相关推荐
一起养小猫9 小时前
Flutter for OpenHarmony 实战:记账应用数据统计与可视化
开发语言·jvm·数据库·flutter·信息可视化·harmonyos
森之鸟9 小时前
多智能体系统开发入门:用鸿蒙实现设备间的AI协同决策
人工智能·harmonyos·m
jin12332210 小时前
React Native鸿蒙跨平台完成剧本杀组队详情页面,可以复用桌游、团建、赛事等各类组队详情页开发
javascript·react native·react.js·ecmascript·harmonyos
_waylau10 小时前
【HarmonyOS NEXT+AI】问答08:仓颉编程语言是中文编程语言吗?
人工智能·华为·harmonyos·鸿蒙·仓颉编程语言·鸿蒙生态·鸿蒙6
前端菜鸟日常11 小时前
鸿蒙开发实战:100 个项目疑难杂症汇编
汇编·华为·harmonyos
jin12332211 小时前
基于React Native鸿蒙跨平台移动端表单类 CRUD 应用,涵盖地址列表展示、新增/编辑/删除/设为默认等核心操作
react native·react.js·ecmascript·harmonyos
摘星编程13 小时前
OpenHarmony环境下React Native:DatePicker日期选择器
react native·react.js·harmonyos
一起养小猫13 小时前
Flutter for OpenHarmony 实战:番茄钟应用完整开发指南
开发语言·jvm·数据库·flutter·信息可视化·harmonyos
一起养小猫13 小时前
Flutter for OpenHarmony 实战:数据持久化方案深度解析
网络·jvm·数据库·flutter·游戏·harmonyos
不爱吃糖的程序媛14 小时前
Cordova/Capacitor 在鸿蒙生态中的实践与展望
华为·harmonyos