积分143 / 贡献0

提问0答案被采纳0文章10

[经验分享] OpenHarmony应用如何上传下载文件 原创

深开鸿_石悌君 显示全部楼层 发表于 2023-12-18 11:02:52

简介:

使用@ohos.request接口创建上传和下载任务,实现上传、下载功能

文档环境:

  • 开发环境:Windows 10家庭版
  • DevEco Studio版本:DevEco Studio 4.0Release (4.0.0.600)
  • SDK版本:4.0.10.13 (full sdk)
  • API版本:Version 10
  • 开发板型号:DAYU200(RK3568)
  • 系统版本:OpenHarmony 4.1.2.2

演示demo:

  • 设置request.agent.Config类型的上传/下载任务的配置信息:action和url是必选配置,action值为request.agent.Action.UPLOAD和request.agent.Action.DOWNLOAD,url值为资源地址
  • 通过 let context = getContext(this) as common.UIAbilityContext并使用request.agent.create(context, config)创建上传或下载任务
  • 通过on(‘progress’)订阅任务进度的事件,可以得到已上传/下载的字节数,app自定义算法显示上传下载进度比例显示在用户界面
  • 通过on(‘completed’)订阅任务完成事件,on(‘failed’)订阅任务失败事件
  • 上述准备工作完成后,调用Task的start函数开始文件上传下载
  • 上传/下载演示界面如图
上传 下载
upload.jpg download.jpg
  • 上传文件核心代码如下
import common from '@ohos.app.ability.common';
import request from '@ohos.request';
import promptAction from '@ohos.promptAction';

class Upload {
  async uploadFile(fileUris: Array<string>, begin: number, end: number, callback: (progress: number, isSucceed: boolean) => void): Promise<void> {
    // 查询到存在正在执行的上传任务,提示并返回
    let tasks = await request.agent.search({
      state: request.agent.State.RUNNING,
      action: request.agent.Action.UPLOAD,
      mode: request.agent.Mode.FOREGROUND
    });
    if (tasks.length > 0) {
      promptAction.showToast({ message: $r('app.string.have_upload_task_tips'), bottom: TOAST_BOTTOM });
      return;
    }
    let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
    let config: request.agent.Config = {
      action: request.agent.Action.UPLOAD,
      headers: HEADER,
      url: await urlUtils.getUrl(context),
      mode: request.agent.Mode.FOREGROUND,
      method: 'POST',
      title: 'upload',
      network: request.agent.Network.ANY,
      data: await this.getFilesAndData(context.cacheDir, fileUris),
      token: UPLOAD_TOKEN,
      index: 0, // 指定片段上传的文件
      begins: begin,
      ends: end
    };

    try {
      this.uploadTask = await request.agent.create(context, config);
      this.uploadTask.on('progress', (progress: request.agent.Progress) => {
        let processed = Number(progress.processed.toString()).valueOf();
        let size = progress.sizes[progress.index];
        if (progress.index === 0) {
          if (end === -1) {
            size -= begin;
          } else {
            size = end - begin + 1;
          }
        }

        let process: number = Math.floor(processed / size * 100);
        if (process < 100) {
          callback(process, false);
        }
      });
      this.uploadTask.on('completed', (progress: request.agent.Progress) => {
        callback(100, true);
        this.cancelTask();
      });
      this.uploadTask.on('failed', async (progress: request.agent.Progress) => {
        if (this.uploadTask) {
          let taskInfo = await request.agent.touch(this.uploadTask.tid, UPLOAD_TOKEN);
        }
        callback(100, false);
        this.cancelTask();
      })
      await this.uploadTask.start();
    } catch (err) {
      callback(100, false);
    }
  }
}
  • 下载文件核心代码如下
import common from '@ohos.app.ability.common';
import request from '@ohos.request';
import promptAction from '@ohos.promptAction';

class RequestDownload {
  async downloadFile(folder: string, url: string, callback: (progress: number, isSuccess: boolean) => void) {
    // 查询到存在正在执行的下载任务,提示并返回
    let tasks = await request.agent.search({
      state: request.agent.State.RUNNING,
      action: request.agent.Action.DOWNLOAD,
      mode: request.agent.Mode.FOREGROUND
    });
    if (tasks.length > 0) {
      promptAction.showToast({ message: $r('app.string.have_download_task_tips'), bottom: TOAST_BOTTOM });
      return;
    }
    let splitUrl = url.split('//')[1].split('/');
    let context: common.UIAbilityContext = getContext(this) as common.UIAbilityContext;
    let downloadConfig: request.agent.Config = {
      action: request.agent.Action.DOWNLOAD,
      url: url,
      method: 'POST',
      title: 'download',
      mode: request.agent.Mode.FOREGROUND,
      network: request.agent.Network.ANY,
      saveas: `./${folder}/${splitUrl[splitUrl.length-1]}`,
      overwrite: true
    }

    try {
      this.downloadTask = await request.agent.create(context, downloadConfig);
      this.downloadTask.on('progress', (progress: request.agent.Progress) => {
        let processed = Number(progress.processed.toString()).valueOf();
        let size = progress.sizes[0];
        let process: number = Math.floor(processed / size * 100);
        if (process < 100) {
          callback(process, false);
        }
      })
      this.downloadTask.on('completed', (progress: request.agent.Progress) => {
        callback(100, true);
        this.deleteTask();
      })
      this.downloadTask.on('failed', async (progress: request.agent.Progress) => {
        if (this.downloadTask) {
          let taskInfo = await request.agent.show(this.downloadTask.tid);
        }
        callback(100, false);
        this.deleteTask();
      })
      await this.downloadTask.start();
    } catch (err) {
      callback(100, false);
    }
  }
}

sample仓地址:

本功能的sample仓地址:https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Connectivity/UploadAndDownLoad

©著作权归作者所有,转载或内容合作请联系作者

您尚未登录,无法参与评论,登录后可以:
参与开源共建问题交流
认同或收藏高质量问答
获取积分成为开源共建先驱

Copyright   ©2023  OpenHarmony开发者论坛  京ICP备2020036654号-3 |技术支持 Discuz!

返回顶部