HarmonyOS鸿蒙Next中从云存储中下载大量文件视频如何保存至相册

HarmonyOS鸿蒙Next中从云存储中下载大量文件视频如何保存至相册 从云存储中下载大量文件视频如何保存至相册?

3 回复

云存储中下载大量文件视频保存至相册可参考文档下载云侧文件至本地,然后通过安全控件、弹窗授权实现媒体资源保存至相册。

  • 方式一:安全控件SaveButton可以临时获取存储权限,而不需要权限弹框授权确认,最终把图片保存到相册。
    参考代码:
import photoAccessHelper from '@ohos.file.photoAccessHelper';
import fs from '@ohos.file.fs';
import { common } from '@kit.AbilityKit';
import { UIContext } from '@kit.ArkUI';

@Entry
@Component
struct saveButtonMethod {
  @State message: string = 'Hello World';
  uiContext: UIContext = this.getUIContext();

  build() {
    Row() {
      Column() {
        SaveButton({ icon: SaveIconStyle.FULL_FILLED, text: SaveDescription.SAVE })
          .onClick(async (_event: ClickEvent, result: SaveButtonOnClickResult) => {
            if (result === SaveButtonOnClickResult.SUCCESS) {
              try {
                let context: Context = this.uiContext.getHostContext() as common.UIAbilityContext;
                let helper = photoAccessHelper.getPhotoAccessHelper(context);
                // onClick触发后一分钟内通过createAsset接口创建图片文件,一分钟后createAsset权限收回。
                let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg');
                // 使用uri打开文件,可以持续写入内容,写入过程不受时间限制
                let file = await fs.open(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
                try {
                  context.resourceManager.getMediaContent($r('app.media.startIcon').id, 0)
                    .then(async value => {
                      let media = value.buffer;
                      // 写到媒体库文件中
                      await fs.write(file.fd, media);
                      await fs.close(file.fd);
                      this.uiContext.showAlertDialog({ message: '已保存至相册!' });
                    });
                } catch (err) {
                  console.error(`error is ${err}`);
                }
              } catch (error) {
                console.error(`error is ${error}`);
              }
            } else {
              this.uiContext.showAlertDialog({ message: '设置权限失败' });
            }
          });
      }
      .width('100%');
    }
    .height('100%');
  }
}
  • 方式二:调用showAssetsCreationDialog弹窗授权保存图片到相册。
    使用弹窗授权保存图片到相册,首先获取需要保存到媒体库的位于应用沙箱的图片/视频uri,然后调用showAssetsCreationDialog接口弹窗授权,通过fs.copyFileSync将图片保存到相册。
    示例代码如下:
import { fileIo as fs, fileUri } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { camera, cameraPicker as picker } from '@kit.CameraKit';

@Entry
@Component
struct showAssetsCreationDialogMethod {
  @State message: string = 'SaveButton';
  uiContext: UIContext = this.getUIContext();

  async saveFile() {
    let mContext: Context = this.uiContext.getHostContext() as common.UIAbilityContext;
    let types: Array<picker.PickerMediaType> = [picker.PickerMediaType.PHOTO];
    let pickerProfile: picker.PickerProfile = {
      cameraPosition: camera.CameraPosition.CAMERA_POSITION_BACK,
      videoDuration: 15
    };
    let pickerResult: picker.PickerResult = await picker.pick(mContext,
      types, pickerProfile);
    if (pickerResult.resultCode === 0) {
      // 成功
      let finalUri = pickerResult.resultUri;
      // 保存图片到缓存目录
      let dirpath = (this.uiContext.getHostContext() as common.UIAbilityContext).tempDir + '/cameTem.jpg';
      let dirUri = fileUri.getUriFromPath(dirpath);
      let finalFile = fs.openSync(finalUri, fs.OpenMode.READ_ONLY);
      let dirFile = fs.openSync(dirpath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
      fs.copyFileSync(finalFile.fd, dirFile.fd);
      fs.closeSync(finalFile);
      fs.closeSync(dirFile);
      console.info('ImagePicker', 'Succeeded in copying. ');
      // 删除相册图片(需要申请ohos.permission.WRITE_IMAGEVIDEO权限)
      try {
        await photoAccessHelper.MediaAssetChangeRequest.deleteAssets(this.uiContext.getHostContext(),
          [pickerResult.resultUri]);
        finalUri = dirUri;
      } catch (err) {
        console.error('ImagePicker', `deleteAssetsDemo failed with error: ${err.code}, ${err.message}`);
      }
      console.info('ShowAssetsCreationDialogDemo.');

      // 获取需要保存到媒体库的位于应用沙箱的图片/视频uri
      try {
        let srcFileUris: Array<string> = [dirUri];
        let photoCreationConfigs: Array<photoAccessHelper.PhotoCreationConfig> = [{
          fileNameExtension: 'jpg',
          photoType: photoAccessHelper.PhotoType.IMAGE,
        }];
        let context = this.uiContext.getHostContext() as common.UIAbilityContext;
        let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
        let desFileUris: Array<string> =
          await phAccessHelper.showAssetsCreationDialog(srcFileUris, photoCreationConfigs);
        console.info('showAssetsCreationDialog success, data is ' + desFileUris);
        if (desFileUris.length > 0) {
          try {
            let srcFile = fs.openSync(srcFileUris[0], fs.OpenMode.READ_ONLY);
            let desFile = fs.openSync(desFileUris[0], fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
            fs.copyFileSync(srcFile.fd, desFile.fd);
            fs.closeSync(srcFile);
            fs.closeSync(desFile);
          } catch (e) {
            console.error(e);
          }
        }
      } catch (err) {
        console.error('showAssetsCreationDialog',
          `showAssetsCreationDialog failed with error: ${err.code}, ${err.message}`);
      }
    }
  }

  build() {
    RelativeContainer() {
      Text(this.message)
        .id('SaveButton')
        .fontSize(50)
        .onClick(() => {
          this.saveFile();
        });
    }
    .height('100%')
    .width('100%');
  }
}

【背景知识】
ohos.permission.WRITE_IMAGEVIDEO是受限开放的权限,应用可以通过安全控件或授权弹窗的方式,将指定的媒体资源保存到相册中。

  • 安全控件(SaveButton):安全控件的保存控件,用户通过点击该保存按钮,可以临时获取存储权限,而不需要权限弹框授权确认。使用此控件需要UI样式合法,不合法会导致授权失败,可参考安全控件样式的约束与限制
  • 授权弹窗(showAssetsCreationDialog):通过调用接口拉起保存确认弹窗,基于弹窗授权的方式获取的目标媒体文件uri。用户同意保存后,返回已创建并授予保存权限的uri列表,该列表永久生效,应用可使用该uri写入图片/视频。如果用户拒绝保存,将返回空列表。
  • 下载云侧文件至本地,下载成功后,文件将保存在context.cacheDir目录下。

更多关于HarmonyOS鸿蒙Next中从云存储中下载大量文件视频如何保存至相册的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中,通过云存储下载大量文件视频并保存至相册,需使用媒体库管理接口。调用PhotoAccessHelper模块的createAsset()方法将下载文件写入相册。批量操作建议使用MediaLibrary进行异步处理,避免阻塞主线程。需申请ohos.permission.READ_MEDIAohos.permission.WRITE_MEDIA权限。文件路径通过PhotoAccessHelper.getPhotoAccessHelper()获取相册句柄后操作。

在HarmonyOS Next中,可以通过以下步骤将云存储下载的大量视频文件批量保存到相册:

  1. 使用@ohos.file.fs文件系统API管理下载的文件,通过fs.copyFile()fs.moveFile()将文件从下载目录转移到相册目录(/storage/media/100/local/files/Pictures/)。

  2. 利用@ohos.file.photoAccessHelper相册管理模块的getPhotoAccessHelper()接口获取相册助手,调用createAsset()方法将视频文件创建为相册资源。

  3. 对于批量操作,建议结合后台任务管理(@ohos.backgroundTaskManager)分批次处理,避免阻塞主线程。可通过循环遍历文件列表,逐条调用相册接口完成保存。

注意:需提前申请相册读写权限(ohos.permission.READ_IMAGEVIDEOohos.permission.WRITE_IMAGEVIDEO),并确保云存储下载路径与相册路径访问权限正常。

回到顶部