在鸿蒙Next移动端内嵌H5页面实现文件下载,可以通过以下方式实现:
方案一:使用Web组件下载能力
鸿蒙的Web组件支持文件下载,需要在Web组件的配置中启用下载功能:
import webview from '@ohos.web.webview';
// 创建Web组件
webViewCtrl = webview.WebviewController.create({
id: 'web1',
fileAccess: true // 允许文件访问
})
// 设置下载监听器
webViewCtrl.onFileSelectorShow((event) => {
// 处理文件下载
this.handleFileDownload(event);
})
方案二:JavaScript与Native交互
在H5页面中通过JavaScript调用鸿蒙Native能力:
H5页面代码:
// 触发文件下载
function downloadFile(fileUrl, fileName) {
if (window.ohoswebview && window.ohoswebview.downloadFile) {
// 调用鸿蒙Native方法
window.ohoswebview.downloadFile(fileUrl, fileName);
} else {
// 备用方案:传统下载方式
const link = document.createElement('a');
link.href = fileUrl;
link.download = fileName;
link.click();
}
}
鸿蒙侧代码:
// 注册JavaScript接口
webViewCtrl.registerJavaScriptProxy({
downloadFile: (fileUrl: string, fileName: string) => {
this.downloadManager.download(fileUrl, fileName);
}
}, 'ohoswebview');
方案三:完整的文件下载实现
import fileio from '@ohos.fileio';
import request from '@ohos.request';
class FileDownloader {
async downloadFile(fileUrl: string, fileName: string) {
try {
// 创建下载任务
const config: request.DownloadConfig = {
url: fileUrl,
filePath: this.getDownloadPath(fileName),
overwrite: true
};
const downloadTask = await request.download(config);
// 监听下载进度
downloadTask.on('progress', (receivedSize: number, totalSize: number) => {
const progress = (receivedSize / totalSize * 100).toFixed(2);
console.log(`下载进度: ${progress}%`);
});
// 下载完成
downloadTask.on('complete', () => {
console.log('文件下载完成');
});
} catch (error) {
console.error('下载失败:', error);
}
}
private getDownloadPath(fileName: string): string {
const context = getContext(this) as common.UIAbilityContext;
return context.filesDir + '/' + fileName;
}
}
关键配置
在module.json5中添加权限:
{
"module": {
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
},
{
"name": "ohos.permission.WRITE_USER_STORAGE"
}
]
}
}
注意事项
- 权限申请:确保应用有网络和存储权限
- 文件路径:使用应用沙箱目录存储下载文件
- 安全考虑:验证下载文件的来源和类型
- 用户体验:提供下载进度提示和完成通知
推荐使用方案二,通过JavaScript与Native交互的方式,既能保持H5页面的灵活性,又能利用鸿蒙系统的文件管理能力。