HarmonyOS:基于axios实现文件的下载以及下载进度的监听

#前言:项目开发中,避免不了实现文件下载功能,其他平台的下载都很成熟,网上的例子也比较多,我就自己项目中实现的下载功能做个总结,你可以参考我的写法实现功能。 下载封装基于axios实现的下载功能。

1.下载文件url:xxx

2.文件操作封装类:FileUtil ,是桃花源长老的文件封装库,第三方库,各种工具类很多,很方便

3.下载方法:dowLoadFileCallBack

4.下载封装:axiosClient.downLoadFil

简单的介绍,详细的下载步骤如下:

//下载方法,开始下载

kotlin 复制代码
startDownLoadFileTask(){
    //下载文件路径
    let testUrl ='xxx'
    if (FileUtil.accessSync(this.fileSavePath)&&this.downLoadFile.fileDownLoadStatus =='3') {
      WinLog.info('文件存在,不用下载直接打开')
      this.previewFileMethod();
      return;
    }
    //先删除旧的未下载完毕的文件
    if (FileUtil.accessSync(this.fileSavePath)) {
      FileUtil.unlinkSync(this.fileSavePath);
    }
    HttpRequest.dowLoadFileCallBack(testUrl,this.fileSavePath,({
      onResult:(downLoadInfo:WinDownloadFileModel)=>{
        //下载状态值,主要是用来区分图片的展示状态
        this.downStatusName = 'ic_downing_status';
        if (this.progress==100) {
          this.downStatusName = 'ic_play_status';
        }
        if (downLoadInfo.fileDownLoadStatus=='3') {
          downLoadInfo.fileUrl = this.downLoadFile.fileUrl;
          this.downLoadFile.fileDownLoadStatus = '3';
          //更新本地数据库状态
          BaseDownFileQueryManager.updateDownFileTableData(downLoadInfo);
        }
        //下载进度条的值显示
        this.progress = downLoadInfo.fileDownProgress;
        //计算下载的文件大小
        this.fileSize = `文件大小:${FileUtil.getFormatFileSize(downLoadInfo.fileLength)}`
      }
    }),({
      onError:(error:string)=>{
        this.downStatusName = 'ic_needdown_status';
        WinLog.error('下载文件报错:'+ error);
        this.downLoadFile.fileDownLoadStatus = '2';
      }
    }))
  }
HttpRequest类,下载的方法

/*

  • 文件下载方法
  • @param url下载地址
  • @param filePath文件路径
  • @param successCallBack成功回调
  • @param failureCallBack
  • */
typescript 复制代码
static dowLoadFileCallBack(url:string,filePath:string,successCallBack?:DownLoadCallback,failureCallBack?:DownLoadErrorCallback){
    const commonHeader: AxiosHeaders = new AxiosHeaders()
    commonHeader.set('Accept-Language', i18n.System.getSystemLanguage())
    commonHeader.set('User-Agent', commonUtils.getUserAgent())
    commonHeader.set('Content-Type', 'application/x-www-form-urlencoded')
    axiosClient.downLoadFile(filePath,{
      url: url,
      headers: commonHeader,
      showLoading: false,
    },successCallBack,failureCallBack);
  }
}
//自定义封装的回调类
export interface DownLoadCallback {
  /**
   * 下载回调
   * @param popInfo
   */
  onResult?: (downLoadingInfo: WinDownloadFileModel) => void;
}
export interface DownLoadErrorCallback {
  onError?: (error: string) => void;
}
文件下载的具体实现方法,主要是基于axios的文件下载方法,进行了二次封装,适用于自己的项目下载,你也可以参看我的方法,改成适合你的项目用法,都是很简单的,我这个只是单文件的下载,还没进行多文件同时下载,多文件下载需要进行线程控制,以及队列控制。
ini 复制代码
/*
   * 文件下载
   * **/
  downLoadFile(filePath:string,config?: HttpRequestConfig,successCallBack?:DownLoadCallback,failureCallBack?:DownLoadErrorCallback){
    axios({
      url: config?.url,
      method: 'get',
      context: getContext(this),
      filePath: filePath ,
      onDownloadProgress: (progressEvent: AxiosProgressEvent): void => {
        //下载回掉,状态设置,以及进度的回调
        let downProgressModel = new WinDownloadFileModel();
        if (progressEvent.total&&progressEvent.total>0) {
          downProgressModel.fileDownLoadStatus = '2';
          downProgressModel.fileDownProgress = NumberUtil.toFloat((progressEvent.loaded / progressEvent.total * 100).toFixed(2).toString());
          downProgressModel.fileLength = progressEvent.total;
          if (successCallBack&&successCallBack.onResult) {
            successCallBack.onResult(downProgressModel);
          }
        }else {
          downProgressModel.fileDownLoadStatus = '1';
          downProgressModel.fileDownProgress = 0
          if (successCallBack&&successCallBack.onResult) {
            successCallBack.onResult(downProgressModel);
          }
        }
      }
    }).then((res: AxiosResponse<string>) => {
     //下载完毕的回调
      winLog.info('down load finish:'+ JSON.stringify(res));
      let downProgressModel = new WinDownloadFileModel();
      downProgressModel.fileDownLoadStatus = '3';
      downProgressModel.fileDownProgress = 100;
      //计算下载文件的大小
      let fileSize = FileUtil.getFileDirSize(filePath);
      downProgressModel.fileLength = fileSize;
          if (successCallBack&&successCallBack.onResult) {
            successCallBack.onResult(downProgressModel);
          }    
        
     }).catch((error: AxiosError) =>{
      //下载失败的回调
      if (failureCallBack&&failureCallBack.onError) {
        failureCallBack.onError(error.message);
      }
    })
  }

这些代码就可以实现单文件的下载,以及进度条的展示,以及下载状态的更新。有什么疑问可以随时询问,感谢mark。

相关推荐
KjPrime2 小时前
纯vue手写流程组件
前端·javascript·vue.js
码农不惑3 小时前
前端开发:Vue以及Vue的路由
前端·javascript·vue.js
烛阴5 小时前
JavaScript instanceof:你真的懂它吗?
前端·javascript
shadouqi6 小时前
1.angular介绍
前端·javascript·angular.js
痴心阿文6 小时前
React如何导入md5,把密码password进行md5加密
前端·javascript·react.js
hdk19936 小时前
Edge浏览器登录微软账户报错0x80190001的解决办法
前端·microsoft·edge
徐同保7 小时前
yarn 装包时 package里包含[email protected]报错
前端·javascript
群联云防护小杜7 小时前
分布式节点池:群联云防护抗DDoS的核心武器
前端·网络·分布式·udp·npm·node.js·ddos
冬冬小圆帽8 小时前
验证码设计与前端安全:实现方式、挑战与未来发展趋势深度分析
前端·安全