一:效果图
二:添加依赖
import fs from '@ohos.file.fs';//文件管理
import picker from '@ohos.file.picker'//选择器
三:下载,保存图片的实现
// 下载图片imgUrl
downloadAndSaveImage(imgUrl: string) {
http.createHttp()
.request(imgUrl,
(error, data: http.HttpResponse) => {
if (error) {
promptAction.showToast({
message: '下载失败',
duration: 2000
})
return
}
if (data.result instanceof ArrayBuffer) {
this.pickerSave(data.result as ArrayBuffer)
}
})
}
//保存图片
async pickerSave(buffer: ArrayBuffer): Promise<void> {
const photoSaveOptions = new picker.PhotoSaveOptions() // 创建文件管理器保存选项实例
photoSaveOptions.newFileNames = ['PhotoView' + new Date().getTime() + '.jpg']//创建一个开头为PhotoView_xxxx_.jpg的图片
const photoViewPicker = new picker.PhotoViewPicker
photoViewPicker.save(photoSaveOptions)
.then(async (photoSaveResult) => {
let uri = photoSaveResult[0]
let file = await fs.open(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
await fs.write(file.fd, buffer)
await fs.close(file.fd)
promptAction.showToast({
message: "保存成功"
})
})
.catch(error => {
console.log('downloadAndSaveImage 保存失败:', error)
promptAction.showToast({
message: "保存失败"
})
})
}
四:在Page中的使用
@Entry
@Component
struct ImgPage {
@State imageUrl: string =""
aboutToAppear(){
const params = router.getParams()
if (params) {
this.imageUrl = params['imageUrl']//https:xxxxxx.png
if (!this.imageUrl) {
console.error("imageUrl 加载失败: imageUrl 为空");
}
}
}
build() {
Column() {
Stack().height(30)
HeadlineBar({
title:"详情",
heightBar: 45,
fontSize:20,
closeCallback: () => {
router.back()
}
})
// 显示每个图片
Image(this.imageUrl)
.alt($r('app.media.icon'))// 使用alt,在网络图片加载成功前使用占位图
.width(300)
.height(400)
.margin({top:30})
.borderRadius(8)
Button('立即下载')
.fontSize(15)
.width(131)
.height(54)
.margin({
top:30
})
.onClick(()=>{
if (this.imageUrl) {
weatherApi.downloadAndSaveImage(this.imageUrl)
}
})
}
.width('100%')
.height('100%')
}
}