#鸿蒙通关秘籍#如何使用鸿蒙Web组件主动发起一个下载任务?

HarmonyOS
5天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
紫霞仙子SQL

可以通过startDownload()方法在鸿蒙的Web组件中主动发起下载任务。开发者需先注册下载代理DownloadDelegate,然后通过指定下载地址触发下载。实现过程如下:

bash import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit';

@Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate();

build() { Column() { Button('setDownloadDelegate') .onClick(() => { try { this.delegate.onBeforeDownload((webDownloadItem: webview.WebDownloadItem) => { webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); }) this.delegate.onDownloadUpdated((webDownloadItem: webview.WebDownloadItem) => { console.log("download update guid: " + webDownloadItem.getGuid()); }) this.delegate.onDownloadFailed((webDownloadItem: webview.WebDownloadItem) => { console.log("download failed guid: " + webDownloadItem.getGuid()); }) this.delegate.onDownloadFinish((webDownloadItem: webview.WebDownloadItem) => { console.log("download finish guid: " + webDownloadItem.getGuid()); }) this.controller.setDownloadDelegate(this.delegate); } catch (error) { console.error(ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}); } }) Button('startDownload') .onClick(() => { try { this.controller.startDownload('https://www.example.com/'); } catch (error) { console.error(ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}); } }) Web({ src: 'www.example.com', controller: this.controller }) } } }

分享
微博
QQ
微信
回复
5天前
相关问题
Web组件如何发起一个下载任务
441浏览 • 1回复 待解决