HarmonyOS 如何下载网络图片

昨天一个需求是在预览大图的时候,提供一个下载按钮,并且支持下载到相册中,网上搜出来的文档大部分都是可下载到沙箱中,在咨询过鸿蒙技术人员以后得知,可以使用保存组件(https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/savebutton-V5),使用的时候需要特别注意UI要求,不能把组件置于屏幕边缘,否则会权限申请失败,看代码中如何使用的


SaveButton()
            .width(this.isShowRelevantMe ? '50%' : '100%')
            .height(40)
            .fontSize(12)
            .backgroundColor(Color.Black)
            .iconSize(16)
            .onClick(async (event: ClickEvent, result: SaveButtonOnClickResult) => {
              if (result === SaveButtonOnClickResult.SUCCESS) {
                const context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
                // 免去权限申请和权限请求等环节,获得临时授权,保存对应图片
                saveHttpPhoto(this.fileList[this.imageIndex].filePath, context)
              } else {
                Toast.showToast('下载失败')
              }
            })
        }
        .width('90%')
        .padding({ bottom: 5 })
        .height('100%')


static async saveHttpPhoto(url: string, context: common.UIAbilityContext) {
    // 使用request下载图片并在回调函数中保存图片到相册
    http.createHttp().request(url,
      {
        method: http.RequestMethod.GET,
        connectTimeout: 60000,
        readTimeout: 60000
      },
      async (error: BusinessError, data: http.HttpResponse) => {
        if (error) {
          console.error(`http reqeust failed with. Code: ${error.code}, message: ${error.message}`);
        } else {
          if (http.ResponseCode.OK === data.responseCode) {
            let imageBuffer: ArrayBuffer = data.result as ArrayBuffer;
            try {
              // 获取相册路径
              let helper = photoAccessHelper.getPhotoAccessHelper(context);
              let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg')
              let file = await fileIo.open(uri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE)
              // 写入文件
              await fileIo.write(file.fd, imageBuffer);
              // 关闭文件
              await fileIo.close(file.fd);
              Toast.showToast('已保存至相册');
            } catch (error) {
              console.error("error is " + JSON.stringify(error))
              Toast.showToast("error is " + JSON.stringify(error));
            }
          } else {
            console.error("error occurred when image downloaded!")
            Toast.showToast("error occurred when image downloaded!")
          }
        }
      })
  }

api12已测试通过,开发环境版本5.0.3

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

落魄的Android开发

感谢支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值