HarmonyOS 视频照片下载到沙箱并读取

现在我的页面1中有一张照片,一个视频。

现在点击下载按钮,需要把这张图片和视频下载到应用内。

并且在 页面2 中读取所下载的照片和视频

HarmonyOS
2024-12-25 14:51:13
650浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
fox280

下载demo参考如下,需要在module.json5配置如下权限

‘requestPermissions’: [
{“name”: “ohos.permission.INTERNET”},
{“name”: “ohos.permission.WRITE_MEDIA”},
{“name”: “ohos.permission.READ_NEDIA”}
],
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
import common from '@ohos.app.ability.common';
import request from '@ohos.request';
import { BusinessError } from '@ohos.base';

// 获取应用文件路径
let context = getContext(this) as common.UIAbilityContext;
let filesDir = context.filesDir;

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

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
        Button("下载")
        .onClick(() => {
          try {
            console.log('downloadTask1 filesDir' + filesDir + '/00sg00izg2.jpg');
            //下载文件
            request.downloadFile(context, {
              url: 'https://xxx.jpg',
              filePath: filesDir + '/00sg00izg2.jpg'
            }).then((downloadTask: request.DownloadTask) => {
              //开启回调
              downloadTask.on('complete', () => {
                console.info('downloadTask1 complete');
              })
            }).catch((err: BusinessError) => {
              console.error(Invoke downloadTask failed, code is ${err.code}, message is ${err.message});
            });
          } catch (error) {
            let err: BusinessError = error as BusinessError;
            console.error(Invoke downloadTask downloadFile failed, code is ${err.code}, message is ${err.message});
          }
        })

          .width('100%')
      }
      .height('100%')
    }
  }}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.

参考链接

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-request-V5#downloadconfig

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/app-file-upload-download-V5

Image组件不能直接传入应用沙箱路径,需要传入应用沙箱uri;

解决方法:拿到文件的沙箱路径后,通过调用@ohos.file.fileuri模块的fileuri.getUriFromPath(file.path)将沙箱路径转化为沙箱uri,传入之后即可正常显示。

参考文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-file-fileuri-V5

分享
微博
QQ
微信
回复
2024-12-25 17:59:27
相关问题
HarmonyOS 相机拍照完,照片读取失败
674浏览 • 1回复 待解决
HarmonyOS关于下载到缓存目录的问题
1655浏览 • 1回复 待解决
HarmonyOS 下载到本地文件的预览问题
960浏览 • 1回复 待解决
HarmonyOS hap包下载到手机上怎么安装
1144浏览 • 1回复 待解决
HarmonyOS 如何读取沙箱 sql 文件为string
499浏览 • 1回复 待解决
HarmonyOS webview如何播放本地沙箱视频
2824浏览 • 1回复 待解决
HarmonyOS 怎么下载图片显示
695浏览 • 1回复 待解决