logo
积分中心
鸿蒙开发——下载网络资源文件
头像 蓝亭书序 2026-11-18 13:37:14    发布
0 浏览 0 收藏

1、概 述

文件下载是一个非常常见的应用场景,我们可以通过使用ArkTs提供的上传下载模块(ohos.request)的下载接口将网络资源文件下载到应用文件目录。

另外,对已下载的网络资源文件,我们可以使用基础文件IO接口(ohos.file.fs)对其进行访问,使用方式与应用文件访问一致。

文件下载过程使用系统服务代理完成(在api12中request.agent.create接口增加了设置代理地址参数,支持我们设置自定义代理地址)。

2、示 例

下载文件一般可以使用两种方式来实现:1)使用downloadFile接口;2)使用agent接口;

需要注意,下载文件需要申请网络权限:ohos.permission.INTERNET。

申明方式,在module.json5中配置对应字段,示例如下:


{
  "module" : {
    // ...
    "requestPermissions":[
      {
        "name" : "ohos.permission.INTERNET",
        "reason": "$string:reason",
        "usedScene": {
          "abilities": [
            "FormAbility"
          ],
          "when":"inuse"
        }
      }
    ]
  }
}


我们以下载一份txt文件为例,图片下载url链接如下:


https://gitee.com/lantingshuxu/harmony-class-room-demos/raw/main/readme.md


2.1、通过downloadFile接口下载文件

一般情况下,如果我们不需要做其他额外配置,可以优先使用downloadFile接口来实现文件下载。

示例:我们通过downloadFile接口下载txt完毕后,本地打开再显示出来。效果如下:

图片

代码如下(注意28~48行downloadFile方法和49~58行readDownloadedFile方法):


import { common } from '@kit.AbilityKit';
import fs from '@ohos.file.fs';
import { BusinessError, request } from '@kit.BasicServicesKit';
import { buffer } from '@kit.ArkTS';
@Entry
@Component
export struct RequestDownloadPage {
  @State url: string = 'https://gitee.com/lantingshuxu/harmony-class-room-demos/raw/main/readme.md';
  @State logText: string = '';
  appendLogText(log: string) {
    this.logText = `${this.logText}\n${log}`;
  }
  getDownloadFilePath() {
    // 获取应用文件路径
    let context = getContext(this) as common.UIAbilityContext;
    let filesDir = context.filesDir;
    return `${filesDir}/readme.md`;
  }
  async checkAndRemoveFile(path: string) {
    const exist = await fs.access(path);
    if (exist) {
      this.appendLogText('文件:' + path + ' 已存在,即将删除');
      await fs.unlink(path);
      this.appendLogText('文件:' + path + ' 已删除');
    }
  }

  async downloadFile() {
    this.logText = '';
    try {
      // 获取应用文件路径
      const filePath = this.getDownloadFilePath();
      await this.checkAndRemoveFile(filePath);
      let context = getContext(this) as common.UIAbilityContext;
      request.downloadFile(context, { url: this.url, filePath })
        .then((downloadTask: request.DownloadTask) => {
          downloadTask.on('complete', () => {
            this.appendLogText('文件下载完毕');
            this.readDownloadedFile(filePath);
          })
        }).catch((err: BusinessError) => {
        this.appendLogText(`Invoke downloadTask failed, code is ${err.code}, message is ${err.message}`);
      });
    } catch (error) {
      let err: BusinessError = error as BusinessError;
      this.appendLogText(`Invoke downloadFile failed, code is ${err.code}, message is ${err.message}`);
    }
  }
  readDownloadedFile(filePath: string) {
    this.appendLogText('准备打开本地文件');
    let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE);
    let arrayBuffer = new ArrayBuffer(1024);
    let readLen = fs.readSync(file.fd, arrayBuffer);
    let buf = buffer.from(arrayBuffer, 0, readLen);
    console.info(`The content of file: ${buf.toString()}`);
    this.appendLogText('下面是文件内容:\n------\n\n' + buf.toString());
    fs.closeSync(file);
  }
  build() {
    NavDestination() {
      Button('下载文件')
        .onClick(() => {
          this.downloadFile();
        })
      Text(this.logText)
    }
    .title('Request-Download下载文件')
  }
}



2.2、通过agent接口下载文件

界面效果与2.1小节的相同,代码如下(注意28~59行downloadFile方法和60~68行readDownloadedFile方法):


import { common } from '@kit.AbilityKit';
import fs from '@ohos.file.fs';
import { BusinessError, request } from '@kit.BasicServicesKit';
import { buffer } from '@kit.ArkTS';
@Entry
@Component
export struct RequestDownloadPage {
  @State url: string = 'https://gitee.com/lantingshuxu/harmony-class-room-demos/raw/main/readme.md';
  @State logText: string = '';
  appendLogText(log: string) {
    this.logText = `${this.logText}\n${log}`;
  }
  getDownloadFilePath() {
    // 获取应用文件路径
    let context = getContext(this) as common.UIAbilityContext;
    let filesDir = context.filesDir;
    return `${filesDir}/readme.md`;
  }
  async checkAndRemoveFile(path: string) {
    const exist = await fs.access(path);
    if (exist) {
      this.appendLogText('文件:' + path + ' 已存在,即将删除');
      await fs.unlink(path);
      this.appendLogText('文件:' + path + ' 已删除');
    }
  }

  async downloadFile() {
    let context = getContext(this) as common.UIAbilityContext;
    const path = this.getDownloadFilePath();
    await this.checkAndRemoveFile(path);
    let config: request.agent.Config = {
      action: request.agent.Action.DOWNLOAD,
      url: this.url,
      saveas: path,
      gauge: true,
      overwrite: true,
      network: request.agent.Network.WIFI,
    };
    request.agent.create(context, config)
      .then((task: request.agent.Task) => {
        task.start((err: BusinessError) => {
          if (err) {
            this.appendLogText(`Failed to start the download task, Code: ${err.code}  message: ${err.message}`);
            return;
          }
        });
        task.on('progress', async (progress) => {
          this.appendLogText(`/Request download status ${progress.state}, downloaded ${progress.processed}`);
        })
        task.on('completed', async () => {
          this.readDownloadedFile(path);
          //该方法需用户管理任务生命周期,任务结束后调用remove释放task对象
          request.agent.remove(task.tid);
        })
      }).catch((err: BusinessError) => {
      this.appendLogText(`Failed to create a download task, Code: ${err.code}, message: ${err.message}`);
    });
  }
  readDownloadedFile(filePath: string) {
    this.appendLogText('准备打开本地文件');
    let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE);
    let arrayBuffer = new ArrayBuffer(1024);
    let readLen = fs.readSync(file.fd, arrayBuffer);
    let buf = buffer.from(arrayBuffer, 0, readLen);
    this.appendLogText('下面是文件内容:\n------\n\n' + buf.toString());
    fs.closeSync(file);
  }
  build() {
    NavDestination() {
      Button('下载文件')
        .onClick(() => {
          this.downloadFile();
        })
      Text(this.logText)
    }
    .title('Request-Download下载文件')
  }
}



©本站发布的所有内容,包括但不限于文字、图片、音频、视频、图表、标志、标识、广告、商标、商号、域名、软件、程序等,除特别标明外,均来源于网络或用户投稿,版权归原作者或原出处所有。我们致力于保护原作者版权,若涉及版权问题,请及时联系我们进行处理。
分类
HarmonyOS

暂无评论数据

加载中...

发布

地址:北京市朝阳区北三环东路三元桥曙光西里甲1号第三置业A座1508室 电话:13391790444或(010)62178877
版权所有:电脑商情信息服务集团 北京赢邦策略咨询有限责任公司
声明:本媒体部分图片、文章来源于网络,版权归原作者所有,我司致力于保护作者版权,如有侵权,请与我司联系删除

京ICP备:2022009079号-2

京公网安备:11010502051901号

ICP证:京B2-20230255