HarmonyOS 鸿蒙Next 通过http下载图片到相册,能提供一份完整的demo吗
HarmonyOS 鸿蒙Next 通过http下载图片到相册,能提供一份完整的demo吗
参考demo如下:
import common from '@ohos.app.ability.common';
import fs, { ReadOptions, WriteOptions } from '@ohos.file.fs';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { BusinessError, request } from '@kit.BasicServicesKit';
import { buffer } from '@kit.ArkTS';
// 获取应用文件路径
let context = getContext(this) as common.UIAbilityContext;
let cacheDir = context.cacheDir;
async function readWriteFile(): Promise<void> {
let helper = photoAccessHelper.getPhotoAccessHelper(context);
let uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, ‘jpg’);
let destFile = await fs.open(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
// 打开文件
let srcFile = fs.openSync(cacheDir + ‘/a.jpg’, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
// 读取源文件内容并写入至目的文件
let bufSize = 4096;
let readSize = 0;
let buf = new ArrayBuffer(bufSize);
let readOptions: ReadOptions = {
offset: readSize,
length: bufSize
};
let readLen = fs.readSync(srcFile.fd, buf, readOptions);
while (readLen > 0) {
readSize += readLen;
let writeOptions: WriteOptions = {
length: readLen
};
fs.writeSync(destFile.fd, buf, writeOptions);
readOptions.offset = readSize;
readLen = fs.readSync(srcFile.fd, buf, readOptions);
}
// 关闭文件
fs.closeSync(srcFile);
fs.closeSync(destFile);
}
@Entry
@Component
struct Index {
@State message: string = ‘Save Demo’;
downLoad(){
try {
request.downloadFile(context, {
url: ‘https://copyright.bdstatic.com/vcg/creative/cc9c744cf9f7c864889c563cbdeddce6.jpg@h_1280’,
filePath: cacheDir + ‘/a.jpg’
}).then((downloadTask: request.DownloadTask) => {
downloadTask.on(‘complete’, () => {
console.info(‘download complete’);
let file = fs.openSync(cacheDir + ‘/a.jpg’, fs.OpenMode.READ_WRITE);
let arrayBuffer = new ArrayBuffer(1024);
let readLen = fs.readSync(file.fd, arrayBuffer);
let buf = buffer.from(arrayBuffer, 0, readLen);
console.info(The content of file: ${buf.toString()}
);
fs.closeSync(file);
})
}).catch((err: BusinessError) => {
console.error(Invoke downloadTask failed, code is ${err.code}, message is ${err.message}
);
});
} catch (error) {
let err: BusinessError = error as BusinessError;
console.error(Invoke downloadFile failed, code is ${err.code}, message is ${err.message}
);
}
}
build() {
RelativeContainer() {
Text(this.message)
.id(‘SaveDemo’)
.fontSize(50)
.fontWeight(FontWeight.Bold)
.alignRules({
center: { anchor: ‘container’, align: VerticalAlign.Center },
middle: { anchor: ‘container’, align: HorizontalAlign.Center }
})
.onClick(()=>{
//this.downLoad()
})
SaveButton({text:SaveDescription.SAVE_IMAGE}).onClick(async (_event: ClickEvent, result: SaveButtonOnClickResult) => {
if (result == SaveButtonOnClickResult.SUCCESS) {
readWriteFile()
}
else {
AlertDialog.show({ message: “设置权限失败” })
}
})
}
.height(‘100%’)
.width(‘100%’)
}
}
以下是一份HarmonyOS 鸿蒙Next通过http下载图片到相册的完整demo:
首先,在module.json5文件中配置必要的权限:
"requestPermissions": [
{
"name": "ohos.permission.INTERNET",
"reason": "用于访问网络"
},
{
"name": "ohos.permission.WRITE_IMAGEVIDEO",
"reason": "用于写入图片到图库"
}
]
接下来是代码实现:
import { http } from '@kit.NetworkKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { fileIo } from '@kit.CoreFileKit';
import common from '@ohos.app.ability.common';
@Entry
@Component
struct SaveNetworkImage {
async saveImage(url: string): Promise<void> {
try {
const response = await http.createHttp().request(url);
const imageBuffer = response.result as ArrayBuffer;
const context = getContext(this) as common.UIAbilityContext;
const helper = photoAccessHelper.getPhotoAccessHelper(context);
const uri = await helper.createAsset(photoAccessHelper.PhotoType.IMAGE, 'jpg');
const file = await fileIo.open(uri, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
await fileIo.write(file.fd, imageBuffer);
await fileIo.close(file.fd);
} catch (e) {
console.error(e);
}
}
}
在需要下载图片的地方调用saveImage
方法并传入图片URL即可。
如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html