实现拷贝文件到沙箱功能鸿蒙示例代码 原创

鸿蒙场景化示例代码技术工程师
发布于 2025-4-8 10:15
浏览
0收藏

本文原创发布在华为开发者社区

介绍

本示例基于openSync、writeSync接口实现了拷贝文件到沙箱。

实现拷贝文件到沙箱功能源码链接

效果预览

实现拷贝文件到沙箱功能鸿蒙示例代码-鸿蒙开发者社区

使用说明

点击按钮拷贝,拷贝之后即可保存图片文件。

实现思路

1.使用openSync、writeSync接口实现了拷贝文件到沙箱

 context.resourceManager.getRawFileContent('startIcon.png', (err: BusinessError, data: Uint8Array) => {
    if (err != null) {
      Logger.error('open file failed: ' + err.message)
    } else {
      let buffer = data.buffer
      let sandboxPath = context.filesDir
      Logger.info('myRawfileCopy path' + sandboxPath)
      let file = fs.openSync(context.filesDir + '/test.png', fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE)
      try {
        // 拷贝文件到沙箱
        fs.writeSync(file.fd, buffer)
        fs.close(file.fd)
      } catch (err) {
        Logger.info('myRawfileCopy error')
      }

    }
  })
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.

2.保存到媒体库

 // 获取需要保存到媒体库的位于应用沙箱的图片/视频uri
    let srcFileUris: Array<string> = [
      fileUri.getUriFromPath(context.filesDir+ '/test.png')
    ];
    let photoCreationConfigs: Array<photoAccessHelper.PhotoCreationConfig> = [
      {
        title: 'test2', // 可选
        fileNameExtension: 'png',
        photoType: photoAccessHelper.PhotoType.IMAGE,
        subtype: photoAccessHelper.PhotoSubtype.DEFAULT, // 可选
      }
    ];
    let desFileUris: Array<string> = await phAccessHelper.showAssetsCreationDialog(srcFileUris, photoCreationConfigs);
    let file1 = fs.openSync(context.filesDir+ '/test.png', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
    let arrayBuffer = new ArrayBuffer(4096000);
    let readLen = fs.readSync(file1.fd, arrayBuffer);
    let buf = buffer.from(arrayBuffer, 0, readLen);
    Logger.info('content of File: ' + buf.toString());
    let file2 = fs.openSync(desFileUris[0], fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
    fs.closeSync(file2);
    fs.closeSync(file1);
    Logger.info('showAssetsCreationDialog success, data is ' + desFileUris);
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
分类
收藏
回复
举报


回复
    相关推荐