当前位置: 首页> 教育> 锐评 > HarmonyOS 如何下载网络图片

HarmonyOS 如何下载网络图片

时间:2025/7/11 15:23:33来源:https://blog.csdn.net/qq_32136827/article/details/140497753 浏览次数:1次

昨天一个需求是在预览大图的时候,提供一个下载按钮,并且支持下载到相册中,网上搜出来的文档大部分都是可下载到沙箱中,在咨询过鸿蒙技术人员以后得知,可以使用保存组件(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

关键字:HarmonyOS 如何下载网络图片

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: