HarmonyOS鸿蒙Next中下载文件保存到本地
HarmonyOS鸿蒙Next中下载文件保存到本地 第一次点击下载 保存在本地 第二次再次点击 这个时候 文件已经在本地了 如何判断 文件已经存在 不走下载 而是直接找到这个文件
Button("保存2").onClick(() => {
try {
request.downloadFile(context, {
url: "https://cfmoto.oss-cn-hangzhou.aliyuncs.com/upload/audio/AE863091060020422/audio_1.mp3",
filePath: filesDir + '/11.mp3'
}).then((downloadTask: request.DownloadTask) => {
downloadTask.on('complete', () => {
let file = fs.openSync(filesDir + '/11.mp3', fs.OpenMode.READ_WRITE);
console.info('file.fd: ' + file.fd)
console.info('file.fd: ' + JSON.stringify(filesDir + '/11.mp3'))
let arrayBuffer = new ArrayBuffer(1024);
let readLen = fs.readSync(file.fd, arrayBuffer);
let buf = buffer.from(arrayBuffer, 0, readLen);
console.info('file.fd1: ' + JSON.stringify(buf))
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}`);
}
})
更多关于HarmonyOS鸿蒙Next中下载文件保存到本地的实战教程也可以访问 https://www.itying.com/category-93-b0.html
3 回复
try {
const fileExists = await fs.accessSync(filePath);
if (fileExists) {
console.info('文件已存在,进行操作...');
this.processExistingFile(filePath);
} else {
console.info('文件不存在,开始下载...');
this.downloadFile(url, filePath);
console.info('文件下载完成');
this.processExistingFile(filePath);
}
} catch (err) {
console.error('操作失败:', err);
}
更多关于HarmonyOS鸿蒙Next中下载文件保存到本地的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中下载文件并保存到本地,可以使用DownloadManager服务。首先,通过getSystemService(Context.DOWNLOAD_SERVICE)获取DownloadManager实例。然后,创建DownloadManager.Request对象,设置下载URL和保存路径。最后,调用downloadManager.enqueue(request)开始下载。下载完成后,文件将保存到指定路径,可通过DownloadManager查询下载状态和文件位置。


