中国优质的IT技术网站
专业IT技术创作平台
IT职业在线教育平台
Web组件如何发起一个下载任务?
微信扫码分享
import web_webview from '@ohos.web.webview'; import business_error from '@ohos.base'; @Entry @Component struct Index { webviewController: web_webview.WebviewController = new web_webview.WebviewController(); delegate: web_webview.WebDownloadDelegate = new web_webview.WebDownloadDelegate(); build() { Column() { Button('设置WebDownloadDelegate') .onClick(() => { try { this.delegate.onBeforeDownload((webDownloadItem: web_webview.WebDownloadItem) => { console.log("will start a download."); // 传入一个下载路径,并开始下载。 webDownloadItem.start("/data/storage/el2/base/cache/web/" + webDownloadItem.getSuggestedFileName()); }) this.delegate.onDownloadUpdated((webDownloadItem: web_webview.WebDownloadItem) => { console.log("download update guid: " + webDownloadItem.getGuid()); }) this.delegate.onDownloadFailed((webDownloadItem: web_webview.WebDownloadItem) => { //下载失败 }) this.delegate.onDownloadFinish((webDownloadItem: web_webview.WebDownloadItem) => { //下载结束 }) this.webviewController.setDownloadDelegate(this.delegate); } catch (error) { let e:business_error.BusinessError = error as business_error.BusinessError; console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); } }) Button('开始下载') .onClick(() => { try { // 这里指定下载地址为 https://www.example.com/,Web组件会发起一个下载任务将该页面下载下来。 // 开发者需要替换为自己想要下载的内容的地址。 this.webviewController.startDownload('https://www.example.com/'); } catch (error) { let e:business_error.BusinessError = error as business_error.BusinessError; console.error(`ErrorCode: ${e.code}, Message: ${e.message}`); } }) Web({ src: 'www.example.com', controller: this.webviewController }) } .width('100%') .height('100%') .justifyContent(FlexAlign.Center) } }