HarmonyOS鸿蒙Next中将沙箱文件里面的视频(.mp4)文件保存到手机相册

HarmonyOS鸿蒙Next中将沙箱文件里面的视频(.mp4)文件保存到手机相册

先在module.json5里面配置

{
  "name": "ohos.permission.WRITE_IMAGEVIDEO",
  "reason": "$string:write_media_reason",
  "usedScene": {
    "abilities": [
      "EntryAbility"
    ],
    "when": "inuse"
  }
},
{
  "name": "ohos.permission.READ_IMAGEVIDEO",
  "reason": "$string:read_media_reason",
  "usedScene": {
    "abilities": [
      "EntryAbility"
    ],
    "when": "inuse"
  }
}

使用 showAssetsCreationDialog 来保存视频

const context = getContext(this);
let filesDir = context.filesDir;
let uri: string = filesDir + `${this.item.iSrc}`; //沙箱的文件路径
console.log(`-=-=uri:${uri}`)
let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
try {
  // 指定待保存到媒体库的位于应用沙箱的图片uri
  let srcFileUri = uri;
  let srcFileUris: Array<string> = [
    fileUri.getUriFromPath(uri)
  ];
  // 指定待保存照片的创建选项,包括文件后缀和照片类型,标题和照片子类型可选
  let photoCreationConfigs: Array<photoAccessHelper.PhotoCreationConfig> = [
    {
      // title: `${this.item.name}`, // 可选
      fileNameExtension: 'mp4',
      photoType: photoAccessHelper.PhotoType.VIDEO,
      // subtype: photoAccessHelper.PhotoSubtype.DEFAULT, // 可选
    }
  ];
  // 基于弹窗授权的方式获取媒体库的目标uri
  let desFileUris: Array<string> = await phAccessHelper.showAssetsCreationDialog(srcFileUris, photoCreationConfigs);
  // 将来源于应用沙箱的照片内容写入媒体库的目标uri
  let desFile: fs.File = await fs.open(desFileUris[0], fs.OpenMode.WRITE_ONLY);
  let srcFile: fs.File = await fs.open(srcFileUri, fs.OpenMode.READ_ONLY);
  await fs.copyFile(srcFile.fd, desFile.fd);
  fs.closeSync(srcFile);
  fs.closeSync(desFile);
  promptAction.showToast({
    message: '保存成功!!!请到相册查看' ,
    duration: 3000
  })
  console.info('create asset by dialog successfully');
} catch (err) {
  console.error(`failed to create asset by dialog successfully errCode is: ${err.code}, ${err.message}`);
}

更多关于HarmonyOS鸿蒙Next中将沙箱文件里面的视频(.mp4)文件保存到手机相册的实战教程也可以访问 https://www.itying.com/category-93-b0.html

1 回复

更多关于HarmonyOS鸿蒙Next中将沙箱文件里面的视频(.mp4)文件保存到手机相册的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS鸿蒙Next中,将沙箱文件中的视频(.mp4)保存到手机相册,可以通过以下步骤实现:

  1. 获取文件路径:首先,获取沙箱中视频文件的路径。
  2. 使用MediaStore API:通过MediaStore API将视频文件插入到系统的媒体库中。
  3. 保存到相册:调用MediaStore.Video.Media.insertContentUri方法,将视频文件保存到相册。

示例代码:

ContentValues values = new ContentValues();
values.put(MediaStore.Video.Media.DISPLAY_NAME, "video.mp4");
values.put(MediaStore.Video.Media.MIME_TYPE, "video/mp4");
values.put(MediaStore.Video.Media.RELATIVE_PATH, Environment.DIRECTORY_MOVIES);

Uri uri = getContentResolver().insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values);
try (OutputStream out = getContentResolver().openOutputStream(uri)) {
    Files.copy(Paths.get(sandboxFilePath), out);
}

确保在AndroidManifest.xml中声明了WRITE_EXTERNAL_STORAGE权限。

回到顶部