【文件】【资源】将media目录下的资源文件拷贝至沙盒目录

43 阅读1分钟

​在鸿蒙系统中,media资源目录文件无法直接获取路径,如需要对该资源进行文件级的操作(如系统分享api,参数是fileuri),则需先通过resourceManager.getMediaContentSync读取内容后写入沙箱,之后对沙盒文件进行相关的操作。 下面的代码实现将media资源目录中的文件拷贝至沙盒目录

import { resourceManager } from '@kit.AbilityKit';
import { fileIo } from '@kit.CoreFileKit';

copyMediaFileToSandBox() {
 let context = getContext(this) as common.UIAbilityContext;
 // 读取 mediafile 文件内容
 const mediaFileContent = context.resourceManager.getMediaContentSync('example.jpg');
 // 写入沙箱后获取路径
 const targetPath = `${context.filesDir}/example.jpg`;
 let file = fileIo.openSync(targetPath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
 let writeLen = fileIo.writeSync(file.fd, (mediaFileContent as Uint8Array).buffer);
 console.info("write data to file succeed and size is:" + writeLen);
 fileIo.closeSync(file);
}