HarmonyOS鸿蒙Next中下载提示下载完成无错误状态找不到下载的文件
HarmonyOS鸿蒙Next中下载提示下载完成无错误状态找不到下载的文件 下载视频,无错误并提示下载完成,但是在模拟器或手机上均无法找到下载的文件。
//单文件下载
async downloadFile(folder: string, url: string, callback: (progress: number, isSuccess: boolean) => void) {
logger.info(TAG, 'RequestDownload downloadFile');
// 查询到存在正在执行的下载任务,提示并返回
let tasks = await request.agent.search({
state: request.agent.State.RUNNING,
action: request.agent.Action.DOWNLOAD,
mode: request.agent.Mode.FOREGROUND
});
if (tasks.length > 0) {
// promptAction.showToast({ message: $r('app.string.have_download_task_tips'), bottom: TOAST_BOTTOM });
return;
}
let splitUrl = url.split('//')[1].split('/');
let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
let downloadConfig: request.agent.Config = {
action: request.agent.Action.DOWNLOAD,
url: url,
method: 'GET',
title: 'download',
mode: request.agent.Mode.FOREGROUND,
network: request.agent.Network.ANY,
saveas: `./${folder}${splitUrl[splitUrl.length-1]}`,
overwrite: true
}
logger.info(TAG, `RequestDownload downloadFile, url = ${url}`);
logger.info(TAG, `RequestDownload downloadFile, downloadConfig = ${JSON.stringify(downloadConfig)}`);
try {
this.downloadTask = await request.agent.create(context, downloadConfig);
this.downloadTask.on('progress', (progress: request.agent.Progress) => {
logger.info(TAG, `RequestDownload downloadFile progress, progress = ${progress.processed} ${progress.state}`);
let processed = Number(progress.processed.toString()).valueOf();
let size = progress.sizes[0];
let process: number = Math.floor(processed / size * 100);
if (process < 100) {
callback(process, false);
}
})
this.downloadTask.on('completed', (progress: request.agent.Progress) => {
logger.info(TAG, `RequestDownload downloadFile download complete, file= ${url}, progress = ${progress.processed}`);
callback(100, true);
this.deleteTask();
})
this.downloadTask.on('failed', async (progress: request.agent.Progress) => {
if (this.downloadTask) {
let taskInfo = await request.agent.show(this.downloadTask.tid);
logger.info(TAG, `RequestDownload downloadFile fail, resean = ${taskInfo.reason}, faults = ${JSON.stringify(taskInfo.faults)}`);
}
callback(100, false);
this.deleteTask();
})
await this.downloadTask.start();
} catch (err) {
logger.error(TAG, `RequestDownload downloadFile task err, err = ${JSON.stringify(err)}`);
callback(100, false);
}
}
当前网络资源文件仅支持下载至应用文件目录,是无法直接查看的。 您可以使用FilePicker来实现文件保存到本地系统管理,FilePicker对应的官网链接: https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/save-user-file-V5
问题处理思路:可以先通过picker获取到要选择或者保存文件的公共路径,然后通过fs.copyFile进行文件复制,下载完成后可选择保存位置和保存名称
import { BusinessError } from '@kit.BasicServicesKit';
import fs, { ListFileOptions, Filter } from '@ohos.file.fs';
import request from '@ohos.request';
import { picker } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
@Entry
@Component
struct Index {
@State message: string = 'Hello World';
download() {
const context = getContext(this);
const downloadUrl = 'https://xxxxxxxxxxxx.zip';
try {
request.downloadFile(context, {
enableMetered: true,
url: downloadUrl,
filePath: context.filesDir + '/aaaaaa.zip'
}).then((downloadTask: request.DownloadTask) => {
downloadTask.on('fail', (err: number) => {
console.error(`Failed to download the task. Code: ${err}`);
});
downloadTask.on('progress', (receivedSize: number, totalSize: number) => {
console.log('download', "receivedSize:" + (receivedSize / 1024) + " totalSize:" + (totalSize / 1024));
});
downloadTask.on('complete', () => {
//将文件复制到文件夹中
const documentSaveOptions = new picker.DocumentSaveOptions(); // 创建文件管理器保存选项实例
documentSaveOptions.newFileNames = ["aaa.zip"]; // 保存文件名(可选)
const documentViewPicker = new picker.DocumentViewPicker;
documentViewPicker.save(documentSaveOptions)
.then(async (documentSaveResult) => {
let uri = documentSaveResult[0];
console.info('pub uri:' + uri)
// 沙箱路径文件
let sanFile = fs.openSync(context.filesDir+ '/aaaaaa.zip', fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
let pubFile = fs.openSync(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
// 将文件从沙箱路拷贝到公共路径
fs.copyFileSync(sanFile.fd, pubFile.fd)
console.log("-------")
})
console.log('下载完成')
})
.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() {
Column() {
Button('下载')
.onClick(() => {
this.download()
})
}
.height('100%')
.width('100%')
.alignItems(HorizontalAlign.Center)
.justifyContent(FlexAlign.Center)
}
}
}
更多关于HarmonyOS鸿蒙Next中下载提示下载完成无错误状态找不到下载的文件的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
在HarmonyOS鸿蒙Next中,下载提示下载完成但找不到文件的情况,可能是由于以下原因:
-
存储路径问题:下载的文件可能被保存到了默认的下载目录,但不是用户预期的位置。可以检查设备的“文件管理”应用,查看下载文件夹或其他默认存储路径。
-
权限问题:应用可能没有足够的权限访问存储空间,导致文件无法正确保存或显示。确保应用已获得必要的存储权限。
-
文件系统缓存:有时文件系统缓存可能导致文件在下载完成后未立即显示。可以尝试重启设备或手动刷新文件管理器。
-
应用内部缓存:某些应用可能将下载的文件存储在内部缓存中,而不是外部存储。检查应用的设置或缓存目录。
-
文件名或格式问题:下载的文件可能由于文件名或格式问题,无法被系统正确识别或显示。可以尝试使用第三方文件管理器查看。
-
系统或应用Bug:可能是系统或应用本身的Bug导致文件无法正常显示。可以尝试更新系统或应用至最新版本。
-
存储空间不足:如果设备存储空间不足,可能导致文件无法保存。检查设备的存储空间状态。
-
下载中断或失败:虽然提示下载完成,但实际下载可能中断或失败,导致文件不完整或未保存。可以重新尝试下载。
如果以上方法无效,建议查看设备的日志文件或使用开发者工具进一步排查问题。
在HarmonyOS鸿蒙Next中,如果下载提示完成但找不到文件,可能是以下原因:
- 下载路径设置错误,检查默认存储位置或自定义路径;
- 文件被隐藏或误删,使用文件管理器查看隐藏文件或回收站;
- 下载应用权限不足,确保应用有存储权限;
- 系统缓存问题,重启设备或清除下载应用缓存。
建议逐一排查,必要时联系技术支持。