HarmonyOS photoAccessHelperAccessHelper.showAssetsCreationDialog保存图片失败?

点击同意返回的是-3006,也没有给授权的路径。

async  saveImagePath(path:string) {
  console.info('ShowAssetsCreationDialogDemo.');
  //文件不存在
  if(!fileIo.accessSync(path)){
    return;
  }
  let context = getContext(this);
  let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
  try {
    // 获取需要保存到媒体库的位于应用沙箱的图片/视频uri
    let srcFileUris: Array<string> = [
      path // 实际场景请使用真实的uri
    ];
    let photoCreationConfigs: Array<photoAccessHelper.PhotoCreationConfig> = [
      { // 可选
        fileNameExtension: 'jpg',
        photoType: photoAccessHelper.PhotoType.IMAGE,
        subtype: photoAccessHelper.PhotoSubtype.MOVING_PHOTO,// 可选
      }
    ];
    let desFileUris: Array<string> = await phAccessHelper.showAssetsCreationDialog(srcFileUris, photoCreationConfigs);
    let file = await fs.open(desFileUris[0],fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
    await fs.copy(path,desFileUris[0])
    await fs.close(file.fd)
    promptAction.showToast({ message: '已保存至相册!' });
  } catch (err) {
    console.error('showAssetsCreationDialog failed, errCode is ' + err.code + ', errMsg is ' + err.message);
    promptAction.showToast({ message: '保存失败,请稍后再试' });
  }
}
阅读 459
1 个回答

参考demo:

import { common } from '@kit.AbilityKit';
import { fileIo as fs, fileUri, ReadOptions, WriteOptions } from '@kit.CoreFileKit'
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import json from '@ohos.util.json';

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  filePath: string = '';

  build() {
    Column() {
      Button("复制文件到沙箱")
        .onClick(() => {
          console.log('开始复制文件到沙箱')
          this.copyFile()
          console.log('复制文件到沙箱完成')
        })
      Button('沙箱文件保存到相册')
        .onClick(()=>{
          console.log('开始沙箱文件保存到相册')
          this.syncToSysAlbum(photoAccessHelper.PhotoType.IMAGE,'png', this.filePath)
        })
      Button('沙箱文件保存到相册')
        .onClick(() => {
          console.log('开始沙箱文件保存到相册')
          this.example()
        })
    }
    .height('100%')
    .width('100%')
  }

  copyFile() {
    console.log("开发复制文件")
    let context = getContext(this) as common.UIAbilityContext;
    let srcFileDescriptor = context.resourceManager.getRawFdSync('background.png'); //这里填rawfile文件夹下的文件名(包括后缀)
    let stat = fs.statSync(srcFileDescriptor.fd)
    console.log(`stat isFile:${stat.isFile()}`);
    // 通过UIAbilityContext获取沙箱地址filesDir,以Stage模型为例
    let pathDir = context.filesDir;
    console.log("沙箱文件目录路径:", pathDir)
    let dstPath = pathDir + "/background.png";
    this.filePath = fileUri.getUriFromPath(dstPath)
    console.log("沙箱文件URI" + this.filePath);
    let dest = fs.openSync(dstPath, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE)
    let bufsize = 4096
    let buf = new ArrayBuffer(bufsize)
    let off = 0, len = 0, readedLen = 0
    while (len = fs.readSync(srcFileDescriptor.fd, buf, { offset: srcFileDescriptor.offset + off, length: bufsize })) {
      readedLen += len
      fs.writeSync(dest.fd, buf, { offset: off, length: len })
      off = off + len
      if ((srcFileDescriptor.length - readedLen) < bufsize) {
        bufsize = srcFileDescriptor.length - readedLen
      }
    }
    fs.close(dest.fd)
  }

  async syncToSysAlbum(fileType: photoAccessHelper.PhotoType, extension: string, ...filePath: string[]) {
    //此处获取的phAccessHelper实例为全局对象,后续使用到phAccessHelper的地方默认为使用此处获取的对象,如未添加此段代码报phAccessHelper未定义的错误请自行添加
    let context = getContext(this);
    let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
    try {
      const srcFileUris: string[] = []
      filePath.forEach((path) => {
        srcFileUris.push(path)
      })
      const config: photoAccessHelper.PhotoCreationConfig[] = []
      config.push({
        title: 'background', // 可选
        fileNameExtension: extension,
        photoType: fileType,
        subtype: photoAccessHelper.PhotoSubtype.DEFAULT, // 可选
      })
      console.log("syncToSysAlarm fileUri:" + json.stringify(srcFileUris) + ",config:" + json.stringify(config))
      const desFileUris = await phAccessHelper.showAssetsCreationDialog(srcFileUris, config)
      console.debug(`目标图片 uri is : ${JSON.stringify(desFileUris)}`)
      if (desFileUris.length > 0) {
        for (let index = 0; index < desFileUris.length; index++) {
          this.copyFileContentTo(srcFileUris[index], desFileUris[index])
        }
      }
    } catch (err) {
      console.log("syncToSysAlarm filePath:" + filePath + ",error:" + json.stringify(err))
    }
  }

  async example() {
    console.info('ShowAssetsCreationDialogDemo.');
    let context = getContext(this) as common.UIAbilityContext
    let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
    try {
      let srcFileUri: Array<string> = [this.filePath]
      console.debug(`图片 uri is : ${JSON.stringify(srcFileUri)}`)

      let photoCreationConfigs: Array<photoAccessHelper.PhotoCreationConfig> = [
        {
          title: 'background', // 可选
          fileNameExtension: 'png',
          photoType: photoAccessHelper.PhotoType.IMAGE,
          subtype: photoAccessHelper.PhotoSubtype.DEFAULT, // 可选
        }
      ];
      console.log("syncToSysAlarm fileUri:" + JSON.stringify(srcFileUri) + ",config:" +
      JSON.stringify(photoCreationConfigs))
      let desFileUris: Array<string> = await phAccessHelper.showAssetsCreationDialog(srcFileUri, photoCreationConfigs);
      console.debug(`目标图片 uri is : ${JSON.stringify(desFileUris)}`)


      if (desFileUris.length > 0) {
        for (let index = 0; index < desFileUris.length; index++) {
          this.copyFileContentTo(srcFileUri[index], desFileUris[index])
        }
      }

    } catch (err) {
      console.error('showAssetsCreationDialog failed, errCode is ' + err.code + ', errMsg is ' + err.message);
    }
  }

  /**
   * 复制文件内容到目标文件
   * @param srcFilePath 源文件路径
   * @param destFilePath 目标文件路径
   */
  copyFileContentTo(srcFilePath: string, destFilePath: string) {
    let srcFile = fs.openSync(srcFilePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
    let destFile = fs.openSync(destFilePath, 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);
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进