ArkUI request API实现下载进度获取及显示

系统 OpenHarmony
我们基于ArkUI-ts来实现一个下载进度条的显示,以API 8、FA模型为例。

想了解更多关于开源的内容,请访问:

​51CTO 开源基础软件社区​

​https://ost.51cto.com​

简介

在OpenHarmony应用开发中,我们常用两种方式来实现文件的下载:

  • 使用系统能力SystemCapability.Communication.NetStack(@ohos.http)
  • 使用系统能力SystemCapability.MiscServices.Download(@ohos.request)

区别

  • 前者下载过程信息不可见,后者会在手机状态栏显示下载会话,并且可被应用监听
  • 前者请求下载后不会对文件作进一步处理,后者会直接保存到指定目录

使用场景

  • 下载大体积文件时监听进度
  • 文件下载直接到本地保存

文档传送门
​HarmonyOS​OpenHarmony

下面,我们基于ArkUI-ts来实现一个下载进度条的显示,以API 8、FA模型为例。
(API 9接口稍有改动,若使用API 9、Stage模型,请参考官方文档​​OpenHarmony​​,但基本的代码思路是不变的。
变动:

  • 相比于API 8的FA模型,加入了Context的传参。
  • 增加了uploadFile()、downloadFile()方法,保留upload()、donwload()方法

实现流程

首先配置网络权限(config.json–>module下添加)。

"reqPermissions": [
{
"name": "ohos.permission.INTERNET"
}
],

支持http(config.json下添加)。

"deviceConfig": {
"default": {
"network": {
"cleartextTraffic": true
}
}
},

1、下载配置

导入系统接口。

import request from '@ohos.request'

DownloadConfig

常用的字段配置:

字段

解释

必填

url

资源目标地址

header

请求头配置

filePath

资源保存路径

其它的字段配置:

字段

解释

必填

title

设置下载会话标题(状态栏)

description

设置下载会话的描述(状态栏)

networkType

允许下载的网络类型:

0x00000001——流量数据

0x00010000——wifi

enableRoaming

是否允许在漫游网络中下载

enableMetered

允许在按流量计费的连接下下载

示例1

例如:通过图片url下载保存到本地的 internal://cache的myDownload/test.png 路径,文件名为test.png

let downloadConfig: request.DownloadConfig = {
url: downloadUrl,
filePath: 'myDownload/test.png',
description: 'Download Test',
}

internal://cache是应用沙箱路径,获取方法:

import featureAbility from "@ohos.ability.featureAbility"
let cacheSandPath = featureAbility.getConext().getCacheDoir()

目前js api只支持在filePath配置在internal://cache下(默认)
我们有两种方式可以访问到下载的文件:一是内部储存目录storage路径file目录;二是只允许本应用访问的沙箱路径cache目录
这个知识点在后面的Image显示会用到。

2、创建下载任务

let downloadTask    
request.download(downloadConfig, (err, data) => {
if (err) {
console.info('xxx--- Failed to request the download. Cause: ' + JSON.stringify(err))
return
}
downloadTask = data
})

3、监听下载事件

request.DownloadTask

方法

解释

on/ off(“progress”)

开启/关闭 进度 监听,返回当前下载大小receivedSize和总大小totalSize

on / off(‘complete’|‘pause’|‘remove’)

开启/关闭 完成|暂停|取消 监听

on / off(‘fail’)

开启/关闭 失败 监听,返回错误码

remove()

移除下载任务,返回boolean值

pause()

暂停下载任务

query()

查询下载实时情况,返回Promise<DownloadInfo>

queryMimeType()

查询下载的任务的 MimeType(媒体类型),返回Promise<string>

request.DownloadInfo

属性

解释

downloadTotalBytes

下载的文件的总大小(int bytes)

downloadedBytes

实时下载大小(int bytes)

downloadId

下载的文件ID

fileName

下载的文件名

filePath

存储文件的URI

status

下载状态代码

targetURI

下载文件的URI

downloadTitle

下载的文件的标题

description

待下载文件的描述信息

failedReason

下载失败原因(非必有)

想要实现下载进度的监听,从上面的方法我们可以找到对应的方法 on(“progress”)。

示例3-1

downloadTask.on('progress', (receiveSize: number, totalSize: number) => {
this.curProgressValue = (receiveSize / totalSize) * 100
this.curTaskDownloadedSize = receiveSize
this.curTaskTotalSize = totalSize
})

经过测试发现,直接使用 on(‘progress’)不一定能监听到实时下载大小和总大小,返回值receivedSize和totalSize可能为0。

因此当on(“progress”)的返回值为0时,我们可以用另外一个方法 query() 来查询实时下载中的进度信息,或是在query() 中使用on(‘progress’)。

示例3-2

进度的监听

let downloadInfoFilePath:string = ''
downloadTask.query().then((downloadInfo:request.DownloadInfo) => {
downloadInfoFilePath = downloadInfo.filePath // 此处返回的路径不同于应用沙箱路径
this.downloadTask = data
this.downloadTask.on('progress', (receiveSize: number, totalSize: number) => {
this.curProgressValue = (receiveSize / totalSize) * 100 // 进度条Progress属性值
this.curTaskDownloadedSize = receiveSize // 实时下载大小
this.curTaskTotalSize = totalSize // 总大小
})
/* 或使用query返回的downloadInfo获取下载进度信息
this.curTaskDownloadedSize = downloadInfo.downloadedBytes
this.curTaskTotalSize = downloadInfo.downloadTotalBytes
this.curProgressValue = (this.curTaskDownloadedSize / this.curTaskTotalSize) * 100
*/
console.info('xxx--- downloadTask queried info:' + JSON.stringify(downloadInfo))
}).catch((err) => {
console.info('xxx--- Failed to query the downloadTask:' + JSON.stringify(err))
})

示例3-3

complete、fail、pause事件的监听。

downloadTask.query().then((downloadInfo:request.DownloadInfo) => {
......
var self = this
var clearListeners = function () {
self.downloadTask.off('progress')
self.downloadTask.off('fail')
self.downloadTask.off('remove')
self.downloadTask.off('complete')
}
this.downloadTask.on('fail', (err) => {
clearListeners()
this.curProgressValue = 0
})
this.downloadTask.on('remove', () => {
clearListeners()
this.curProgressValue = 0
})
this.downloadTask.on('complete', () => {
clearListeners()
this.curProgressValue = 100
// downloadInfoList:string[] 保存下载历史的路径
this.downloadInfoList.push(downloadInfoFilePath)
})
})

4、下载结果反馈

定义一个Progress组件来显示当前下载任务的进度(数字和进度条),当下载任务结束后,显示相关信息:任务成功or失败、保存的位置。

Progress({ value: this.curProgressValue })
.width('90%')
.color(Color.Blue)
.margin(10)

Text显示相关下载信息。

Text('实时下载大小: ' + this.curTaskDownloadedSize + ' B').width('90%').fontSize(25).margin(10)
Text('当前任务大小: ' + this.curTaskTotalSize + ' B').width('90%').fontSize(25).margin(10)
Text('下载储存路径:').width('90%').fontSize(25).margin({ left: 10, right: 10, top: 10, bottom: 5 })

定义Image组件,获取保存路径显示下载的媒体(仅当图片)。
这里访问路径使用的是downloadInfo中的filePath属性,即内部储存路径。

// downloadInfoList:string[] 保存下载历史的路径
ForEach(this.downloadInfoList, item => {
Flex({ justifyContent: FlexAlign.Center }) {
Image(item)
.backgroundColor('#ccc')
.margin(5)
.width('25%')
.aspectRatio(1)
.alignSelf(ItemAlign.Start)
.objectFit(ImageFit.ScaleDown)
Text(item).fontSize(15).padding(10).width('70%')
}.width('95%')
}, item => item)

同时,可以完美地运用上我在这篇文章 #创作者激励#【FFH】自制ArkUI组件-文件管理器(二)悬浮小球 封装好的 文件管理器组件-FilerBall 来检验我们文件下载保存的位置,以及查看更详细的文件信息。

演示图

下载大文件(视频)时

![5fd11464c6fc189aeed7ffada375ce2.jpg](​https://dl-harmonyos.51cto.com/images/202303/b8bd32e55db148d6ad99540c9456ddda6d87fd.jpg?x-oss-process=。

借助​​FilerBall​​组件检验

#创作者激励【FFH】ArkUI request API实现下载进度获取及显示-开源基础软件社区

这里设置images、video、file都保存在沙箱访问路径internal://cache的myDownload/下。

Image回显

#创作者激励【FFH】ArkUI request API实现下载进度获取及显示-开源基础软件社区

代码

downloadDemo(downloadUrl: string, saveUrl?: string) {
var self = this
var clearListeners = function () {
self.downloadTask.off('progress')
self.downloadTask.off('fail')
self.downloadTask.off('remove')
self.downloadTask.off('complete')
}
let downloadConfig: request.DownloadConfig = {
url: downloadUrl,
filePath: 'myDownload/' + saveUrl,
enableMetered: true,
enableRoaming: true,
description: 'Download Test',
}
request.download(downloadConfig, (err, data) => {
if (err) {
console.info('xxx--- Failed to request the download. Cause: ' + JSON.stringify(err))
return
}
let downloadInfoFilePath
this.curProgressValue = 0
this.mes = '开始'
this.downloadTask = data
this.downloadTask.query().then((downloadInfo: request.DownloadInfo) => {
downloadInfoFilePath = downloadInfo.filePath
this.downloadTask.on('progress', (receiveSize: number, totalSize: number) => {
this.curProgressValue = (receiveSize / totalSize) * 100
this.curTaskDownloadedSize = receiveSize
this.curTaskTotalSize = totalSize
})
console.info('xxx--- Download task queried. Data:' + JSON.stringify(downloadInfo))
}).catch((err) => {
console.info('xxx--- Failed to query the download task. Cause:' + JSON.stringify(err))
})

this.downloadTask.on('fail', (err) => {
clearListeners()
this.curProgressValue = 0
this.mes = '失败'
})
this.downloadTask.on('remove', () => {
clearListeners()
this.curProgressValue = 0
this.mes = '取消'
})
this.downloadTask.on('complete', () => {
clearListeners()
this.curProgressValue = 100
this.mes = '完成'
// downloadInfoList保存下载历史的路径
this.downloadInfoList.push(downloadInfoFilePath)
})
})
}

ets使用示例。

Button('下载视频(小)', { type: ButtonType.Capsule })
.width('90%')
.height(50)
.margin(10)
.onClick(() => {
this.curProgressValue = this.curTaskDownloadedSize = this.curTaskTotalSize = 0
this.downloadDemo('https://media.w3.org/2010/05/sintel/trailer.mp4', 'video/')
})

页面代码放在附件资源。

https://ost.51cto.com/resource/2679。

想了解更多关于开源的内容,请访问:

​51CTO 开源基础软件社区​

​https://ost.51cto.com​

责任编辑:jianghua 来源: 51CTO 开源基础软件社区
相关推荐

2023-12-11 17:15:05

应用开发波纹进度条ArkUI

2009-07-22 17:13:21

Asp.Net编程

2022-09-09 14:47:50

CircleArkUI

2009-10-14 17:32:24

VB.NET实现下拉列

2012-05-15 10:05:56

WP7 下载进度

2022-02-17 17:05:31

OpenHarmonWEB前端鸿蒙

2013-01-05 13:50:13

AjaxWebASP.NET MVC

2013-07-21 18:27:15

iOS开发ASIHTTPRequ

2009-08-27 14:01:41

C#进度条

2010-06-07 16:37:30

rsync 下载

2015-03-23 18:11:39

UITableViewswift下拉刷新

2017-01-05 09:17:42

科技新闻早报

2011-07-20 15:49:40

iPhone 数据 进度窗

2009-08-18 09:49:00

C# listview

2024-01-11 15:54:55

eTS语言TypeScript应用开发

2023-12-11 17:20:36

抽屉式导航ArkUI应用开发

2021-01-07 09:35:49

Pythontqdm进度

2022-11-02 16:06:54

ArkUIETS

2022-07-04 16:34:46

流光按钮Stack

2022-10-24 14:49:54

ArkUI心电图组件
点赞
收藏

51CTO技术栈公众号