一、学习笔记
HarmonyOS NEXT API 12
二、代码实例
文件下载
async downloadFile(url: string, result?: (taskInfo: request.agent.TaskInfo | undefined) => void) {
let config: request.agent.Config = {
action: request.agent.Action.DOWNLOAD,
url: url,
mode: request.agent.Mode.BACKGROUND,
overwrite: true, // 覆盖已存在文件
metered: true,
redirect: true,
gauge: false,
precise: false,
}
try {
let downloadTask = await request.agent.create(getContext(), config)
let completeCallback = async () => {
let taskInfo = await request.agent.show(downloadTask.tid)
result?.(taskInfo)
}
let failCallback = async () => {
result?.(undefined)
}
downloadTask?.on('completed', completeCallback);
downloadTask?.on('failed', failCallback);
downloadTask.start()
} catch (err) {
result?.(undefined)
}
}