1. RCP 下载功能简介
RCP 模块是 Harmony NEXT 全新开发的 HTTP 数据请求能力接口,它为上传下载能力专门封装了几个方法,针对下载能力,主要是下载到文件的 downloadToFile 方法:
downloadToFile(url: URLOrString, downloadTo: DownloadToFile): Promise<Response>
复制代码
以及下载到流的 downloadToStream 方法:
downloadToStream(url: URLOrString, downloadTo: DownloadToStream): Promise<Response>
复制代码
两个方法都是通过参数 url 指定下载要请求的地址,通过参数 downloadTo 指定写入的文件或者数据流。
本文将通过一个示例演示 RCP 下载能力的使用,并分别下载到文件和数据流。
2. RCP 下载示例
本示例运行后的界面如图所示:
应用启动后,首先配置要下载的 url 文件地址,然后分别单击“下载到文件”按钮和“下载到流”按钮,RCP 会根据配置自动完成下载。
下面详细介绍创建该应用的步骤。
步骤 1:创建 Empty Ability 项目。
步骤 2:在 module.json5 配置文件加上对权限的声明:
"requestPermissions": [ { "name": "ohos.permission.INTERNET" } ]
复制代码
这里添加了访问互联网的权限。
步骤 3:在 Index.ets 文件里添加如下的代码:
import fs from '@ohos.file.fs';import { rcp } from '@kit.RemoteCommunicationKit';import { BusinessError } from '@kit.BasicServicesKit';
@Entry@Componentstruct Index { //连接、通讯历史记录 @State msgHistory: string = '' //下载地址 @State downloadUrl: string = "http://*.*.*.*:8081/download?filename=demo.txt" scroller: Scroller = new Scroller()
build() { Row() { Column() { Text("RCP下载文件示例") .fontSize(14) .fontWeight(FontWeight.Bold) .width('100%') .textAlign(TextAlign.Center) .padding(10)
Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) { Text("文件地址:") .fontSize(14) .width(80) .flexGrow(0)
TextInput({ text: this.downloadUrl }) .onChange((value) => { this.downloadUrl = value }) .width(110) .fontSize(11) .flexGrow(1) } .width('100%') .padding(10)
Flex({ justifyContent: FlexAlign.End, alignItems: ItemAlign.Center }) { Button("下载到文件") .onClick(() => { this.download2File() }) .width(110) .fontSize(14)
Button("下载到流") .onClick(() => { this.download2Stream() }) .width(100) .fontSize(14) } .width('100%') .padding(10)
Scroll(this.scroller) { Text(this.msgHistory) .textAlign(TextAlign.Start) .padding(10) .width('100%') .backgroundColor(0xeeeeee) } .align(Alignment.Top) .backgroundColor(0xeeeeee) .height(300) .flexGrow(1) .scrollable(ScrollDirection.Vertical) .scrollBar(BarState.On) .scrollBarWidth(20) } .width('100%') .justifyContent(FlexAlign.Start) .height('100%') } .height('100%') }
//下载到文件 download2File() { let localFilePath = getContext(this).tempDir + "/demo.txt"
let downloadToFile: rcp.DownloadToFile = { kind: 'file', file: localFilePath, keepLocal: false } as rcp.DownloadToFile
const session = rcp.createSession(); session.downloadToFile(this.downloadUrl, downloadToFile).then(() => { this.msgHistory += "下载成功\r\n" this.showFileContent(localFilePath) }).catch((err: BusinessError) => { this.msgHistory += `下载失败, err.code = ${err.code}, err.message = ${err.message}\r\n`; }); }
//下载到流 download2Stream() { let localFilePath = getContext(this).tempDir + "/demo.txt" let fileStream = fs.createStreamSync(localFilePath, "w") const streamData: rcp.SyncWriteStream = { writeSync(buffer: ArrayBuffer) { fileStream.writeSync(buffer) } };
let downloadToStream: rcp.DownloadToStream = { kind: 'stream', stream: streamData, //这里stream属性传递fileStream或者streamData都可以运行成功 } as rcp.DownloadToStream
const session = rcp.createSession(); session.downloadToStream(this.downloadUrl, downloadToStream).then(() => { fileStream.flushSync() fileStream.closeSync() this.msgHistory += "下载成功\r\n" this.showFileContent(localFilePath) }).catch((err: BusinessError) => { this.msgHistory += `下载失败, err.code = ${err.code}, err.message = ${err.message}\r\n`; }); }
//显示指定文件的内容 showFileContent(filePath: string) { let content = fs.readTextSync(filePath) this.msgHistory += "下载文件内容:" + content + "\r\n" }}
复制代码
步骤 4:编译运行,可以使用模拟器或者真机。
步骤 5:配置要下载的 url 文件地址,然后分别单击“下载到文件”按钮和“下载到流”按钮,为简化下载后的文件验证,这里假设下载的文件是文本类型,下载成功后会显示下载的内容,最后的界面如下所示:
可以看到,文件成功下载到了本地并读取到了文件的内容。
3. 下载功能分析
要实现下载功能,关键点在 downloadTo 参数的配置,在下载到文件的时候,可以按照路径或者文件描述符等多种方式配置下载写入的文件,也可以指定下载的目录。下载到流的时候,也有多种流类型可以选择,读者可以根据实际需要使用合适的流类型。
(本文作者原创,除非明确授权禁止转载)
本文源码地址:
https://gitee.com/zl3624/harmonyos_network_samples/tree/master/code/rcp/RCPDownloadFileDemo
本系列源码地址:
https://gitee.com/zl3624/harmonyos_network_samples
评论