鸿蒙Next ArkTS中request.downloadfile下载文件时如何显示进度条

在鸿蒙Next中使用ArkTS的request.downloadfile下载文件时,如何实时显示下载进度条?目前只能通过回调获取下载状态,但找不到进度更新的具体实现方法。求教如何监听下载进度并动态更新UI进度条组件?

2 回复

在ArkTS中,用request.downloadFile下载文件时,可以通过onProgressUpdate回调获取进度。在UI中用<Progress>组件绑定进度值,实时更新显示。简单说:监听进度,更新UI,进度条就动起来了!

更多关于鸿蒙Next ArkTS中request.downloadfile下载文件时如何显示进度条的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在鸿蒙Next的ArkTS中,使用request.downloadFile下载文件时,可以通过监听onProgressUpdate回调来获取下载进度,并更新UI显示进度条。以下是具体实现步骤和示例代码:

实现步骤:

  1. 导入模块:确保导入@ohos.net.http和UI相关组件。
  2. 创建下载任务:使用request.downloadFile方法。
  3. 监听进度:在onProgressUpdate回调中计算进度百分比。
  4. 更新UI:将进度值绑定到进度条组件(如<Progress>)。

示例代码:

import { http } from '@ohos.net.http';
import { common } from '@ohos.app.ability.common';

@Entry
@Component
struct DownloadExample {
  @State progress: number = 0; // 进度值(0-100)
  private downloadTask: http.HttpRequest | null = null;

  // 开始下载
  startDownload() {
    let url = 'https://example.com/file.zip'; // 替换为实际文件URL
    let filePath = 'path/to/save/file.zip'; // 替换为本地保存路径

    this.downloadTask = http.request.downloadFile(
      getContext(this) as common.Context,
      {
        url: url,
        filePath: filePath,
        onProgressUpdate: (receivedSize: number, totalSize: number) => {
          if (totalSize > 0) {
            this.progress = Math.round((receivedSize / totalSize) * 100); // 计算百分比
            console.info(`下载进度: ${this.progress}%`);
          }
        }
      },
      (err, data) => {
        if (err) {
          console.error('下载失败:', err);
        } else {
          console.info('下载成功,文件路径:', data.filePath);
        }
        this.downloadTask = null;
      }
    );
  }

  // 取消下载(可选)
  cancelDownload() {
    if (this.downloadTask) {
      this.downloadTask.off('onProgressUpdate');
      this.downloadTask.abort();
      this.downloadTask = null;
    }
  }

  build() {
    Column() {
      // 进度条组件
      Progress({ value: this.progress, total: 100, type: ProgressType.Linear })
        .width('80%')
        .height(20)

      Button('开始下载')
        .onClick(() => {
          this.startDownload();
        })
        .margin(10)

      Button('取消下载')
        .onClick(() => {
          this.cancelDownload();
        })
    }
    .padding(20)
    .width('100%')
  }
}

关键点说明:

  • 进度计算:通过receivedSize(已接收大小)和totalSize(总大小)计算百分比。
  • UI绑定:使用@State修饰的progress变量驱动进度条更新。
  • 任务管理:保留downloadTask引用以便取消下载。

注意事项:

  • 确保网络权限已配置(在module.json5中添加ohos.permission.INTERNET)。
  • 文件路径需使用应用沙箱路径(如getContext(this).filesDir + "/file.zip")。

以上代码实现了下载进度的实时显示,进度条会随下载过程动态更新。

回到顶部