HarmonyOS 如何将图片,视频保存到相册

当用户在我们的app中下载了图片/视频到我们的沙盒目录(cache)文件夹下,如何将这个图片/视频保存到相册中?

HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
FengTianYa

参考demo如下:

import common from '@ohos.app.ability.common';
import fs, { ReadOptions, WriteOptions } from '@ohos.file.fs';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { BusinessError, request } from '@kit.BasicServicesKit';
import { buffer } from '@kit.ArkTS';

// 获取应用文件路径
let context = getContext(this) as common.UIAbilityContext;
let cacheDir = context.cacheDir;

async function readWriteFile(): Promise<void> {
  let helper = photoAccessHelper.getPhotoAccessHelper(context);
  let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg');
  let destFile = await fs.open(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  // 打开文件
  let srcFile = fs.openSync(cacheDir + '/a.jpg', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  // 读取源文件内容并写入至目的文件
  let bufSize = 4096;
  let readSize = 0;
  let buf = new ArrayBuffer(bufSize);
  let readOptions: ReadOptions = {
    offset: readSize,
    length: bufSize
  };
  let readLen = fs.readSync(srcFile.fd, buf, readOptions);
  while (readLen > 0) {
    readSize += readLen;
    let writeOptions: WriteOptions = {
      length: readLen
    };
    fs.writeSync(destFile.fd, buf, writeOptions);
    readOptions.offset = readSize;
    readLen = fs.readSync(srcFile.fd, buf, readOptions);
  }
  // 关闭文件
  fs.closeSync(srcFile);
  fs.closeSync(destFile);
}
@Entry
@Component
struct Index {
  @State message: string = 'Save Demo';
  downLoad(){
    try {
      request.downloadFile(context, {
        url: 'xxxx',
        filePath: cacheDir + '/a.jpg'
      }).then((downloadTask: request.DownloadTask) => {
        downloadTask.on('complete', () => {
          console.info('download complete');
          let file = fs.openSync(cacheDir + '/a.jpg', fs.OpenMode.READ_WRITE);
          let arrayBuffer = new ArrayBuffer(1024);
          let readLen = fs.readSync(file.fd, arrayBuffer);
          let buf = buffer.from(arrayBuffer, 0, readLen);
          console.info(`The content of file: ${buf.toString()}`);
          fs.closeSync(file);
        })
      }).catch((err: BusinessError) => {
        console.error(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
      });
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      console.error(`Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`);
    }
  }
  build() {
    RelativeContainer() {
      Text(this.message)
        .id('SaveDemo')
        .fontSize(50)
        .fontWeight(FontWeight.Bold)
        .alignRules({
          center: { anchor: '__container__', align: VerticalAlign.Center },
          middle: { anchor: '__container__', align: HorizontalAlign.Center }
        })
      SaveButton({text:SaveDescription.SAVE_IMAGE}).onClick(async (_event: ClickEvent, result: SaveButtonOnClickResult) => {
        if (result == SaveButtonOnClickResult.SUCCESS) {
          readWriteFile()
        }
        else {
          AlertDialog.show({ message: "设置权限失败" })
        }
      })
    }
    .height('100%')
    .width('100%')
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
如何将视频保存到相册以及主机端
5623浏览 • 1回复 待解决
HarmonyOS如何将PixelMap保存到相册
609浏览 • 1回复 待解决
有谁知道如何将图片保存到相册
1080浏览 • 1回复 待解决
HarmonyOS 如何将base64的图片保存到相册
1030浏览 • 1回复 待解决
如何将像素点保存到图片文件
2344浏览 • 1回复 待解决
HarmonyOS 图片保存到相册报错
32浏览 • 1回复 待解决
如何将Pixmap保存到本地文件?
508浏览 • 1回复 待解决
HarmonyOS如何图片保存到手机相册
545浏览 • 1回复 待解决
如何图片和文案结合,保存到相册
257浏览 • 0回复 待解决
怎么把视频保存到相册以及主机端?
3901浏览 • 1回复 待解决
获取网络图片保存到相册
1534浏览 • 1回复 待解决