使用http模块下的request方法下载图片,并在该方法的回调函数中保存到相册先申请以下权限:ohos.permission.INTERNET ohos.permission.WRITE_IMAGEVIDEO 其中ohos.permission.WRITE\_IMAGEVIDEO推荐使用临时授权方式,https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/user-file-uri-intro-V5保存网络图片代码如下:// xxx.ets @Entry @Component struct RefreshExample { @State isRefreshing: boolean = false @State arr: String[] = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'] @Builder customRefreshComponent() { Stack() { Row() { LoadingProgress().height(32) Text("正在刷新...").fontSize(16).margin({ left: 20 }) }.alignItems(VerticalAlign.Center) }.width("100%").align(Alignment.Center) } build() { Column() { Refresh({ refreshing: $$this.isRefreshing, builder: this.customRefreshComponent() }) { List() { ForEach(this.arr, (item: string) => { ListItem() { Text('' + item) .width('100%') .height(100) .fontSize(16) .textAlign(TextAlign.Center) .borderRadius(10) .backgroundColor(0xFFFFFF) } }, (item: string) => item) } .onScrollIndex((first: number) => { console.info(first.toString()) }) .width('100%') .height('100%') .divider({ strokeWidth: 1, color: Color.Yellow, startMargin: 10, endMargin: 10 }) .scrollBar(BarState.Off) }.onStateChange((refreshStatus: RefreshStatus) => { console.info('Refresh onStatueChange state is ' + refreshStatus) }).onRefreshing(() => { setTimeout(() => { this.isRefreshing = false }, 2000) console.log('onRefreshing test') }).backgroundColor(0x89CFF0) } } } import { http } from '@kit.NetworkKit' import { BusinessError } from '@kit.BasicServicesKit'; import ResponseCode from '@ohos.net.http'; import { photoAccessHelper } from '@kit.MediaLibraryKit'; import fs from '@ohos.file.fs'; @Entry @Component struct Index { loadImageWithUrl(url: string) { // 使用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 (ResponseCode.ResponseCode.OK === data.responseCode) { let imageBuffer: ArrayBuffer = data.result as ArrayBuffer; try { // 获取相册路径 const context = getContext(this); let helper = photoAccessHelper.getPhotoAccessHelper(context); let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg') let file = await fs.open(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE) // 写入文件 await fs.write(file.fd, imageBuffer); // 关闭文件 await fs.close(file.fd); } catch (error) { console.error("error is "+ JSON.stringify(error)) } } else { console.error("error occurred when image downloaded!") } } }) } }
使用http模块下的request方法下载图片,并在该方法的回调函数中保存到相册先申请以下权限:
其中ohos.permission.WRITE\_IMAGEVIDEO推荐使用临时授权方式,https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/user-file-uri-intro-V5
保存网络图片代码如下: