本文基于 ArkUI request API 實現下載進度獲取及顯示。
在鴻蒙應用開發(fā)中,我們常用兩種方式來實現文件的下載:
使用系統(tǒng)能力:
SystemCapability.Communication.NetStack(@ohos.http)使用系統(tǒng)能力:
SystemCapability.MiscServices.Download(@ohos.request)區(qū)別如下:前者下載過程信息不可見,后者會在手機狀態(tài)欄顯示下載會話,并且可被應用監(jiān)聽;前者請求下載后不會對文件作進一步處理,后者會直接保存到指定目錄。
使用場景如下:
下載大體積文件時監(jiān)聽進度
文件下載直接到本地保存
文檔傳送門:
https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-apis-request-0000001333800457 https://docs.openharmony.cn/pages/v3.2Beta/zh-cn/application-dev/reference/apis/js-apis-request.md/下面,我們基于 ArkUI-ts 來實現一個下載進度條的顯示,以 API 8、FA 模型為例。
API 9 接口稍有改動,若使用 API 9、Stage 模型,請參考官方文檔OpenHarmony,但基本的代碼思路是不變的。
https://docs.openharmony.cn/pages/v3.2Beta/zh-cn/application-dev/reference/apis/js-apis-request.md/變動:相比于 API 8 的 FA 模型,加入了 Context 的傳參;增加了uploadFile()、downloadFile() 方法,保留 upload()、donwload() 方法。
實現流程
首先配置網絡權限(config.json–>module 下添加):
"reqPermissions":[
{
"name":"ohos.permission.INTERNET"
}
],
支持 http(config.json 下添加):
"deviceConfig":{
"default":{
"network":{
"cleartextTraffic":true
}
}
},
①下載配置
導入系統(tǒng)接口:
importrequestfrom'@ohos.request'DownloadConfig
常用的字段配置:

其它的字段配置:

示例 1:例如通過圖片 url 下載保存到本地的 internal://cache 的 myDownload/test.png 路徑,文件名為 test.png。
letdownloadConfig:request.DownloadConfig={
url:downloadUrl,
filePath:'myDownload/test.png',
description:'DownloadTest',
}
internal://cache 是應用沙箱路徑,獲取方法:
importfeatureAbilityfrom"@ohos.ability.featureAbility" letcacheSandPath=featureAbility.getConext().getCacheDoir()目前 js api 只支持在 filePath 配置在 internal://cache 下(默認)。 我們有兩種方式可以訪問到下載的文件:一是內部儲存目錄 storage 路徑 file 目錄;二是只允許本應用訪問的沙箱路徑 cache 目錄。 這個知識點在后面的 Image 顯示會用到。
②創(chuàng)建下載任務
letdownloadTask
request.download(downloadConfig,(err,data)=>{
if(err){
console.info('xxx---Failedtorequestthedownload.Cause:'+JSON.stringify(err))
return
}
downloadTask=data
})
③監(jiān)聽下載事件
request.DownloadTask:

request.DownloadInfo:

想要實現下載進度的監(jiān)聽,從上面的方法我們可以找到對應的方法 on(“progress”)。
示例 3-1
downloadTask.on('progress',(receiveSize:number,totalSize:number)=>{
this.curProgressValue=(receiveSize/totalSize)*100
this.curTaskDownloadedSize=receiveSize
this.curTaskTotalSize=totalSize
})
經過測試發(fā)現,直接使用 on(‘progress’) 不一定能監(jiān)聽到實時下載大小和總大小,返回值 receivedSize 和 totalSize 可能為 0。 因此當 on(“progress”) 的返回值為 0 時,我們可以用另外一個方法 query() 來查詢實時下載中的進度信息,或是在 query() 中使用 on(‘progress’)。 示例 3-2
進度的監(jiān)聽:
letdownloadInfoFilePath: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---downloadTaskqueriedinfo:'+JSON.stringify(downloadInfo))
}).catch((err)=>{
console.info('xxx---FailedtoquerythedownloadTask:'+JSON.stringify(err))
})
示例 3-3
complete、fail、pause 事件的監(jiān)聽:
downloadTask.query().then((downloadInfo:request.DownloadInfo)=>{
......
varself=this
varclearListeners=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)
})
})
④下載結果反饋
定義一個 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)
同時,可以完美地運用上我此前封裝好的文件管理器組件-FilerBall,來檢驗我們文件下載保存的位置,以及查看更詳細的文件信息。
演示圖:

借助FilerBall組件檢驗:
這里設置 images、video、file 都保存在沙箱訪問路徑 internal://cache 的 myDownload/ 下。 Image 回顯: 
代碼如下:
downloadDemo(downloadUrl:string,saveUrl?:string){
varself=this
varclearListeners=function(){
self.downloadTask.off('progress')
self.downloadTask.off('fail')
self.downloadTask.off('remove')
self.downloadTask.off('complete')
}
letdownloadConfig:request.DownloadConfig={
url:downloadUrl,
filePath:'myDownload/'+saveUrl,
enableMetered:true,
enableRoaming:true,
description:'DownloadTest',
}
request.download(downloadConfig,(err,data)=>{
if(err){
console.info('xxx---Failedtorequestthedownload.Cause:'+JSON.stringify(err))
return
}
letdownloadInfoFilePath
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---Downloadtaskqueried.Data:'+JSON.stringify(downloadInfo))
}).catch((err)=>{
console.info('xxx---Failedtoquerythedownloadtask.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/')
})
頁面代碼放在附件資源,請點擊閱讀原文查看。
審核編輯:湯梓紅
-
API
+關注
關注
2文章
2466瀏覽量
66988 -
文件
+關注
關注
1文章
597瀏覽量
26110 -
應用開發(fā)
+關注
關注
0文章
63瀏覽量
9990 -
鴻蒙
+關注
關注
60文章
3012瀏覽量
46152 -
OpenHarmony
+關注
關注
33文章
3970瀏覽量
21339
原文標題:鴻蒙上實現一個“下載進度條”
文章出處:【微信號:gh_834c4b3d87fe,微信公眾號:OpenHarmony技術社區(qū)】歡迎添加關注!文章轉載請注明出處。
發(fā)布評論請先 登錄
請問esp32 ota升級如何獲取更新進度?
ArkUI-X平臺橋接Bridge說明
【HarmonyOS next】ArkUI-X休閑娛樂搞笑日歷【基礎】
iOS開發(fā)ASIHTTPRequest進度追蹤的內容介紹
求助,esp32 ota升級如何獲取更新進度?
如何獲取 OpenAI API Key?API 獲取與代碼調用示例 (詳解教程)
產品列表獲取API接口詳解
產品評論獲取API接口
???????使用 DMM Web API 獲取搜索列表數據
獲取Ozon商品詳情數據的API接口技術指南
基于ArkUI request API實現下載進度獲取及顯示
評論