鸿蒙ArkTs 下载监听完成、进度 DownloadUtils工具类

import request from '@ohos.request';
import fs from '@ohos.file.fs';
import { BusinessError } from '@kit.BasicServicesKit';
import { common, Want } from '@kit.AbilityKit';

export  class DownloadUtils{


  /**
  * 下载文件
  * @param mContext
  * @param url
  * @param destFileDir
  * @param fileName
  * @param callback
  */
  public static downloadFile(mContext:Context,url: string, destFileDir: string, fileName: string ,callback: FileCallback): void{
  //  const filePath = mContext.filesDir + '/' + fileName;
    const filePath =   destFileDir + '/' + fileName;
    try {

      // 判定文件是否存在
      if (fs.accessSync(filePath)) {
        // 删除文件
        fs.unlinkSync(filePath)
      }

      let isHaveFile=fs.accessSync(destFileDir)
      if(!isHaveFile){
        fs.mkdirSync(destFileDir)
      }
        // 下载文件
        request.downloadFile(mContext, { url: url, filePath: filePath, enableMetered: true,
          enableRoaming: true }, (err, data) => {
          if (err) {
            console.error('Failed to request the download. Cause: ' + JSON.stringify(err));
            callback.onError()
          }
          // 监听文件下载的实时情况 receivedSize已下载 totalSize总大小
          data.on('progress', (receivedSize, totalSize) => {
            console.info("upload totalSize:" + totalSize + "  receivedSize:" + receivedSize);
            callback.inProgress(receivedSize,totalSize)
          })
          // 监听文件下载完成
          data.on('complete', () => {
            console.info('Download task completed.');
              callback.onSuccess(filePath)
          })
        });

    } catch (err) {
      console.error('err.code : ' + err.code + ', err.message : ' + err.message);
      callback.onError()
    }
  }

}


interface FileCallback {
  onError: () => void;
  inProgress: (progress: number, total: number) => void;
  onSuccess: (file: string) => void;
}


使用方法

let context = getContext(this) as common.UIAbilityContext;
let url="http://www.fao.fudan.edu.cn/_upload/article/files/f5/53/8b40af524563b9b60049899b2dd3/c9a205b4-4188-4af3-863e-bc4e56872e33.pdf"
const filePath = context.filesDir + '/' + "111.pdf";
DownloadUtils.downloadFile(context, url, filePath, "111.pdf", {
  onError: () => {
    console.error("下载失败");
  },
  inProgress: (progress, total) => {
    console.log(`下载进度:${progress}/${total}`);
  },
  onSuccess: (file) => {
    console.log(`下载成功,文件保存在: ${file}`);
  }
});

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值