HarmonyOS 鸿蒙Next:使用rcp下载文件时,如何在回调中动态返回downloadProgress

发布于 1周前 作者 caililin 来自 鸿蒙OS

HarmonyOS 鸿蒙Next:使用rcp下载文件时,如何在回调中动态返回downloadProgress

使用rcp下载文件时,如何在回调中动态返回downloadProgress

主要代码如下:

import { rcp } from “@kit.RemoteCommunicationKit”;
import { BusinessError, Callback } from ‘@kit.BasicServicesKit’;
import { LogUtil } from ‘./LogUtil’;
import { FileUtil } from ‘./FileUtil’;
import fs from ‘@ohos.file.fs’;

const BASE_URL: string = “”; const HTTP_TIMEOUT: number = 10000;

export class RcpResponse { /** 上传进度 / static uploadProgress: number = 0; /* 下载进度 */ static downloadProgress: number = 0; }

// Define a custom response handler const customHttpEventsHandler: rcp.HttpEventsHandler = { onUploadProgress: (totalSize: number, transferredSize: number) => { // Custom logic for handling upload progress LogUtil.info("Upload progress: " + transferredSize + " of " + totalSize); }, onDownloadProgress: (totalSize: number, transferredSize: number) => { // Custom logic for handling download progress LogUtil.info("Download progress: " + transferredSize + " of " + totalSize); RcpResponse.downloadProgress = Math.ceil(transferredSize / totalSize * 100); }, onDataEnd: () => { // Custom logic for handling data transfer completion LogUtil.info(“Data transfer complete”); }, onCanceled: () => { // Custom logic for handling cancellation LogUtil.info(“Request/response canceled”); }, };

const configuration: rcp.Configuration = { transfer: { autoRedirect: true, timeout: { // 允许建立连接的最长时间 connectMs: HTTP_TIMEOUT, // 允许传输数据的最长时间 transferMs: HTTP_TIMEOUT, } }, tracing: { verbose: true, httpEventsHandler: customHttpEventsHandler, } };

const header: rcp.RequestHeaders = { ‘content-type’: ‘application/json’ }

export class HTTPRequestUtil { /**

  • 下载文件

  • @param url: URL

  • @param toPath: 文件保存路径

  • @returns 通过回调返回 */ static async downloadFile(url: string, filename: string, progressCallback: (progress: number) => void, succeedCallback: (filepath: string) => void, failedCallback:(err: BusinessError) => void) { try { // 获取保存全路径 let finalPath = FileUtil.getFilesDirPath(’’, filename); let fileDir = FileUtil.getFilesDirPath(’’); let fn = FileUtil.getFileName(finalPath); let path = finalPath.replace(fn, “”); let isExists = fs.accessSync(finalPath);

    if (isExists) { fs.unlinkSync(finalPath); } else { if (path != fileDir + ‘/’) { FileUtil.mkdirSync(path, true); } }

    let downloadToFile: rcp.DownloadToFile = { kind: “file”, file: finalPath } as rcp.DownloadToFile

    LogUtil.info(“HTTPRequestUtil download file progress: %” + HTTPRequestUtil.downloadProgress);

    let res = await HTTPRequestUtil.session.downloadToFile(url, downloadToFile);

    progressCallback(RcpResponse.downloadProgress); LogUtil.info("Progress: " + RcpResponse.downloadProgress);

    LogUtil.info("File path: " + finalPath); succeedCallback(finalPath); } catch (err) { LogUtil.error(“HTTPRequestUtil download file error:” + err); failedCallback(err); } }

} <button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>

8 回复

HarmonyOS的开发者模式提供了很多实用的工具,方便我们进行调试和优化。

已解决,简单问题复杂化了,以下是完整代码:

/**
   * 下载文件
   * [@param](/user/param) url: URL
   * [@param](/user/param) toPath: 文件保存路径
   *
   * [@returns](/user/returns) 通过回调返回
   */
   async downloadFile(url: string, filename: string, progressCallback: (progress: number) => void, succeedCallback: (filepath: string) => void, failedCallback:(err: BusinessError) => void) {
     // Define a custom response handler
     const customHttpEventsHandler: rcp.HttpEventsHandler = {
       onDownloadProgress: (totalSize: number, transferredSize: number) => {
         // Custom logic for handling download progress
         console.info("Download progress:", transferredSize, "of", totalSize);
         let proc = Math.ceil(transferredSize / totalSize * 100);
         progressCallback(proc);
       }
     };
 <span class="hljs-comment"><span class="hljs-comment">// Configure tracing settings</span></span>
 <span class="hljs-keyword"><span class="hljs-keyword">const</span></span> tracingConfig: rcp.TracingConfiguration = {
   verbose: <span class="hljs-literal"><span class="hljs-literal">true</span></span>,
   infoToCollect: {
     textual: <span class="hljs-literal"><span class="hljs-literal">true</span></span>,
     incomingHeader: <span class="hljs-literal"><span class="hljs-literal">true</span></span>,
     outgoingHeader: <span class="hljs-literal"><span class="hljs-literal">true</span></span>,
     incomingData: <span class="hljs-literal"><span class="hljs-literal">true</span></span>,
     outgoingData: <span class="hljs-literal"><span class="hljs-literal">true</span></span>,
     incomingSslData: <span class="hljs-literal"><span class="hljs-literal">true</span></span>,
     outgoingSslData: <span class="hljs-literal"><span class="hljs-literal">true</span></span>,
   },
   collectTimeInfo: <span class="hljs-literal"><span class="hljs-literal">true</span></span>,
   httpEventsHandler: customHttpEventsHandler,
 };

 <span class="hljs-comment"><span class="hljs-comment">// Use the configuration in the session creation</span></span>
 <span class="hljs-keyword"><span class="hljs-keyword">const</span></span> session = rcp.createSession({ requestConfiguration: { tracing: tracingConfig } });

 <span class="hljs-keyword"><span class="hljs-keyword">try</span></span> {
  <span class="hljs-comment"><span class="hljs-comment">// 获取保存全路径</span></span>
  <span class="hljs-keyword"><span class="hljs-keyword">let</span></span> finalPath = FileUtil.getFilesDirPath(<span class="hljs-string"><span class="hljs-string">''</span></span>, filename);
  <span class="hljs-keyword"><span class="hljs-keyword">let</span></span> fileDir = FileUtil.getFilesDirPath(<span class="hljs-string"><span class="hljs-string">''</span></span>);
  <span class="hljs-keyword"><span class="hljs-keyword">let</span></span> fn = FileUtil.getFileName(finalPath);
  <span class="hljs-keyword"><span class="hljs-keyword">let</span></span> path = finalPath.replace(fn, <span class="hljs-string"><span class="hljs-string">""</span></span>);
  <span class="hljs-keyword"><span class="hljs-keyword">let</span></span> isExists = fs.accessSync(finalPath);

  <span class="hljs-keyword"><span class="hljs-keyword">if</span></span> (isExists) {
    fs.unlinkSync(finalPath);
  } <span class="hljs-keyword"><span class="hljs-keyword">else</span></span> {
    <span class="hljs-keyword"><span class="hljs-keyword">if</span></span> (path != fileDir + <span class="hljs-string"><span class="hljs-string">'/'</span></span>) {
      FileUtil.mkdirSync(path, <span class="hljs-literal"><span class="hljs-literal">true</span></span>);
    }
  }

  <span class="hljs-keyword"><span class="hljs-keyword">let</span></span> downloadToFile: rcp.DownloadToFile = {
    kind: <span class="hljs-string"><span class="hljs-string">"file"</span></span>,
    file: finalPath
  } as  rcp.DownloadToFile

  await session.downloadToFile(url, downloadToFile);

  LogUtil.info(<span class="hljs-string"><span class="hljs-string">"File path: "</span></span> + finalPath);
  succeedCallback(finalPath);
} <span class="hljs-keyword"><span class="hljs-keyword">catch</span></span> (err) {
  LogUtil.error(<span class="hljs-string"><span class="hljs-string">"HTTPRequestUtil download file error:"</span></span> + err);
  failedCallback(err);
}

}

}<button style="position: absolute; padding: 4px 8px 0px; cursor: pointer; top: 8px; right: 8px; font-size: 14px;">复制</button>

HarmonyOS的分布式技术让我实现了跨设备的无缝协作,工作效率翻倍。

目前是progressCallback(RcpResponse.downloadProgress);这一行返回的进度一直是百分百对么

希望HarmonyOS能继续加强在安全性方面的研发,保护用户的隐私和数据安全。

有要学HarmonyOS AI的同学吗,联系我:https://www.itying.com/goods-1206.html

是的,已经拜读了大佬的ef_tool 👍🏻

ef_rcp预计明后天全新轻装上阵,本部分已更换思路提供解决方案,届时欢迎使用并提出宝贵意见

回到顶部