自学内容网 自学内容网

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


原文地址:https://blog.csdn.net/qq_32136827/article/details/140497753

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!