欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 文化 > 鸿蒙网络编程系列29-RCP下载到文件和流示例

鸿蒙网络编程系列29-RCP下载到文件和流示例

2024/10/23 21:41:01 来源:https://blog.csdn.net/tashanzhishi/article/details/143052565  浏览:    关键词:鸿蒙网络编程系列29-RCP下载到文件和流示例

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下载示例

本示例运行后的界面如图所示:

cke_39095.png

应用启动后,首先配置要下载的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
@Component
struct 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文件地址,然后分别单击“下载到文件”按钮和“下载到流”按钮,为简化下载后的文件验证,这里假设下载的文件是文本类型,下载成功后会显示下载的内容,最后的界面如下所示:

cke_103499.png

可以看到,文件成功下载到了本地并读取到了文件的内容。

3. 下载功能分析

要实现下载功能,关键点在downloadTo参数的配置,在下载到文件的时候,可以按照路径或者文件描述符等多种方式配置下载写入的文件,也可以指定下载的目录。下载到流的时候,也有多种流类型可以选择,读者可以根据实际需要使用合适的流类型。

(本文作者原创,除非明确授权禁止转载)

本文源码地址:

https://gitee.com/zl3624/harmonyos_network_samples/tree/master/code/rcp/RCPDownloadFileDemo

本系列源码地址:

https://gitee.com/zl3624/harmonyos_network_samples

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com