鸿蒙网络编程系列21-使用HttpRequest上传任意文件到服务端示例
liebian365 2024-11-09 13:44 35 浏览 0 评论
1. 前述文件上传功能简介
在前述文章鸿蒙网络编程系列11-使用HttpRequest上传文件到服务端示例中,为简化起见,只描述了如何上传文本类型的文件到服务端,对文件的大小也有一定的限制,只能作为鸿蒙API演示使用,在实际开发中上传的文件类型多样,大小不一,本文将介绍一种适应性更广的方法,可以上传任何类型的文件到服务端,并且不限制文件的大小。
2. 上传任意文件类型示例
本示例运行后的界面如下所示:
可以从图库选择文件或者选择任意文件,并且可以设置上传后的文件名,最后单击“上传”按钮即可上传到服务端。
下面详细介绍创建该应用的步骤。
步骤1:创建Empty Ability项目。
步骤2:在module.json5配置文件加上对权限的声明:
"requestPermissions": [
{
"name": "ohos.permission.INTERNET"
}
]
这里添加了访问互联网的权限。
步骤3:在Index.ets文件里添加如下的代码:
import http from '@ohos.net.http';
import util from '@ohos.util';
import fs from '@ohos.file.fs';
import picker from '@ohos.file.picker';
import systemDateTime from '@ohos.systemDateTime';
import buffer from '@ohos.buffer';
@Entry
@Component
struct Index {
//连接、通讯历史记录
@State msgHistory: string = ''
//上传地址
@State uploadUrl: string = "http://192.168.3.8:8081/upload"
//上传后的文件名
@State uploadFileName: string = ""
//要上传的文件
@State uploadFilePath: string = ""
//是否允许上传
@State canUpload: boolean = false
scroller: Scroller = new Scroller()
build() {
Row() {
Column() {
Text("模拟上传示例")
.fontSize(14)
.fontWeight(FontWeight.Bold)
.width('100%')
.textAlign(TextAlign.Center)
.padding(10)
Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
Text("上传的文件:")
.fontSize(14)
.width(100)
.flexGrow(0)
TextInput({ text: this.uploadFilePath })
.enabled(false)
.width(100)
.fontSize(11)
.flexGrow(1)
}
Flex({ justifyContent: FlexAlign.End, alignItems: ItemAlign.Center }) {
Button("图库选择")
.onClick(() => {
this.selectImgFile()
})
.width(100)
.fontSize(14)
Button("其他文件")
.onClick(() => {
this.selectDocFile()
})
.width(100)
.fontSize(14)
}
.width('100%')
.padding(10)
Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
Text("上传地址:")
.fontSize(14)
.width(80)
.flexGrow(0)
TextInput({ text: this.uploadUrl })
.onChange((value) => {
this.uploadUrl = value
})
.width(110)
.fontSize(11)
.flexGrow(1)
}
.width('100%')
.padding(10)
Flex({ justifyContent: FlexAlign.Start, alignItems: ItemAlign.Center }) {
Text("上传后文件名:")
.fontSize(14)
.width(100)
.flexGrow(0)
TextInput({ text: this.uploadFileName })
.onChange((value) => {
this.uploadFileName = value
})
.width(110)
.fontSize(11)
.flexGrow(1)
Button("上传")
.onClick(() => {
this.uploadFile()
})
.enabled(this.canUpload)
.width(70)
.fontSize(14)
.flexGrow(0)
}
.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%')
}
//构造上传文件的body内容
buildBodyContent(boundary: string, fileName: string, content: Uint8Array, contentType: string = "application/octet-stream") {
let textEncoder = new util.TextEncoder();
//构造文件内容前的部分
let preFileContent = `--${boundary}\r\n`
preFileContent = preFileContent + `Content-Disposition: form-data; name="file"; filename="${fileName}"\r\n`
preFileContent = preFileContent + `Content-Type: ${contentType}\r\n`
preFileContent = preFileContent + '\r\n'
let preArray = textEncoder.encodeInto(preFileContent)
//构造文件内容后的部分
let aftFileContent = '\r\n'
aftFileContent = aftFileContent + `--${boundary}`
aftFileContent = aftFileContent + '--\r\n'
let aftArray = textEncoder.encodeInto(aftFileContent)
//文件前后内容和文件内容组合
let bodyBuf = buffer.concat([preArray, content, aftArray])
return bodyBuf.buffer
}
async copy2Sandbox(srcUri: string, fileName: string): Promise<string> {
let context = getContext(this)
//计划复制到的目标路径
let realUri = context.cacheDir + "/" + fileName
//复制选择的文件到沙箱cache文件夹
try {
let file = await fs.open(srcUri);
fs.copyFileSync(file.fd, realUri)
fs.close(file)
} catch (err) {
this.msgHistory += 'err.code : ' + err.code + ', err.message : ' + err.message;
}
return realUri
}
//上传文件
async uploadFile() {
//上传文件使用的分隔符
let boundary: string = '----ShandongCaoxianNB666MyBabyBoundary' + (await systemDateTime.getCurrentTime(true)).toString()
let sandFile = await this.copy2Sandbox(this.uploadFilePath, this.uploadFileName)
//选择要上传的文件的内容
let fileContent: Uint8Array = new Uint8Array(this.readContentFromFile(sandFile))
//上传请求的body内容
let bodyContent = this.buildBodyContent(boundary, this.uploadFileName, fileContent)
//http请求对象
let httpRequest = http.createHttp();
let opt: http.HttpRequestOptions = {
method: http.RequestMethod.POST,
header: { 'Content-Type': `multipart/form-data; boundary=${boundary}`,
'Content-Length': bodyContent.byteLength.toString()
},
extraData: bodyContent
}
//发送上传请求
httpRequest.request(this.uploadUrl, opt)
.then((resp) => {
this.msgHistory += "响应码:" + resp.responseCode + "\r\n"
this.msgHistory += "上传成功\r\n"
})
.catch((e) => {
this.msgHistory += "请求失败:" + e.message + "\r\n"
})
}
//选择图库文件
selectImgFile() {
let imgPicker = new picker.PhotoViewPicker();
imgPicker.select().then((result) => {
if (result.photoUris.length > 0) {
this.uploadFilePath = result.photoUris[0]
this.msgHistory += "select file: " + this.uploadFilePath + "\r\n";
this.canUpload = true
let segments = this.uploadFilePath.split('/')
//文件名称
this.uploadFileName = segments[segments.length-1]
}
}).catch((e) => {
this.msgHistory += 'PhotoViewPicker.select failed ' + e.message + "\r\n";
});
}
//选择文件
selectDocFile() {
let documentPicker = new picker.DocumentViewPicker();
documentPicker.select().then((result) => {
if (result.length > 0) {
this.uploadFilePath = result[0]
this.msgHistory += "select file: " + this.uploadFilePath + "\r\n";
this.canUpload = true
let segments = this.uploadFilePath.split('/')
//文件名称
this.uploadFileName = segments[segments.length-1]
}
}).catch((e) => {
this.msgHistory += 'DocumentViewPicker.select failed ' + e.message + "\r\n";
});
}
//从文件读取内容
readContentFromFile(fileUri: string): ArrayBuffer {
let file = fs.openSync(fileUri, fs.OpenMode.READ_ONLY);
let fsStat = fs.lstatSync(fileUri);
let buf = new ArrayBuffer(fsStat.size);
fs.readSync(file.fd, buf);
fs.fsyncSync(file.fd)
fs.closeSync(file);
return buf
}
}
步骤4:编译运行,可以使用模拟器或者真机。
步骤5:选择文件,假设单击“图库选择”按钮,弹出图片选择窗口,选择一张图片,如图所示:
步骤6:单击“完成”按钮,返回APP,然后修改上传后文件名,最后单击“上传”按钮上传,如图所示:
步骤7:这样就完成了图片上传,在服务端可以看到上传后的图片:
这样就完成了任意文件的上传。
3. 上传功能分析
要实现上传功能,关键点在构造上传文件body内容,代码如下:
//构造上传文件的body内容
buildBodyContent(boundary: string, fileName: string, content: Uint8Array, contentType: string = "application/octet-stream") {
let textEncoder = new util.TextEncoder();
//构造文件内容前的部分
let preFileContent = `--${boundary}\r\n`
preFileContent = preFileContent + `Content-Disposition: form-data; name="file"; filename="${fileName}"\r\n`
preFileContent = preFileContent + `Content-Type: ${contentType}\r\n`
preFileContent = preFileContent + '\r\n'
let preArray = textEncoder.encodeInto(preFileContent)
//构造文件内容后的部分
let aftFileContent = '\r\n'
aftFileContent = aftFileContent + `--${boundary}`
aftFileContent = aftFileContent + '--\r\n'
let aftArray = textEncoder.encodeInto(aftFileContent)
//文件前后内容和文件内容组合
let bodyBuf = buffer.concat([preArray, content, aftArray])
return bodyBuf.buffer
}
这里把body分为三个部分,分别是上传文件内容前的部分、上传文件内容部分以及上传文件内容后的部分,最后把它们组合到一块,作为request方法options参数的extraData属性,如下所示:
//http请求对象
let httpRequest = http.createHttp();
let opt: http.HttpRequestOptions = {
method: http.RequestMethod.POST,
header: { 'Content-Type': `multipart/form-data; boundary=${boundary}`,
'Content-Length': bodyContent.byteLength.toString()
},
extraData: bodyContent
}
(本文作者原创,除非明确授权禁止转载)
本文源码地址:
HarmonyOSNetworkSamples: 鸿蒙网络编程示例仓库 - Gitee.com
本系列源码地址:
相关推荐
- 深度解密epoll 如何工作的?(epoll基本处理流程)
-
epoll...
- 大乐透第19082期:头奖开出7注1000万分落六地 奖池41亿元
-
2019年7月17日晚开奖的体彩超级大乐透第19082期开奖号码为:前区06、18、20、21、31,后区03、04。本期大乐透前区号码五区比为1:0:3:0:1,二区和四区号码没有给出。当期前区和值...
- 【开奖】4月27日周六:福彩、体彩(2021年4月27日体彩开奖结果)
-
4月27日开奖福彩3D第2019110期:61222选5第2019110期:0812202122排列3第19110期:303排列5第19110期:30305大乐透第19047期:0304...
- “红狒狒”落户哈尔滨铁路局(哈尔滨铁路红肠)
-
这几天,“红人”“红狒狒”在牡丹江机务段可引起了不小的轰动,众粉丝争相与其拍照留念,在该段人气爆棚!“红狒狒”到底何许人也?“红狒狒”,中文名:和谐3D型电力机车;绰号:红狒狒、番茄;制造商:大连机...
- 2D、3D、2.5D,做游戏还是搞噱头?玩家都晕了
-
前言游戏类型就像某种潮流,一种流行罢,另一种接棒成为主流。前两年的新作大多以“开放世界”为标签,在追求纯沙盒的过程中打造出一些细致的分类,比如说“类GTA沙盒”。诚然,纯碎的沙盒游戏并不多见,业内只有...
- 《战神4》PC版宣传片发布 GTX 1070即可60帧畅玩
-
在今年10月的时候索尼PlayStation官方正式宣布圣莫尼卡2018年的《战神4》将于2022年1月14日推出PC版本,官方在今天公布了一段PC版宣传片,并且公开了游戏的配置需求。下面让我们一起来...
- 男星深情好丈夫形象崩塌,半夜搂美女坐大腿,举止亲密
-
近日,于晓光被拍到深夜在酒吧玩,结束后与一名女子一起上车离开。上车后,女子直接坐在了他腿上,他也顺势搂着美女,美女满脸笑容地坐在他腿上玩手机离开。可能有人会好奇,于晓光是谁呢?于晓光是韩国艺人秋瓷炫的...
- d3d12dll丢失怎么修复?d3d12dll加载失败怎么解决?
-
d3d12.dll丢失怎么修复?d3d12.dll加载失败怎么解决?很多朋友想要运行游戏的时候都会遇到这个问题,这种情况该怎么办呢?今天系统之家小编给朋友们讲讲具体的解决方法,操作其实还蛮简单的。...
- 许多玩家反馈《生化4RE》PC一直崩溃 无法进入游戏
-
今日(3月24日),卡普空《生化危机4:重制版》正式发售,然而有部分PC玩家遇到了游戏崩溃等问题。很多玩家在贴吧发帖称游戏遇到了严重的崩溃问题,且经常反复,报错代码普遍为FatalD3Derror...
- 微软正式推出适用于WSL Linux的D3D12 GPU视频加速技术
-
今天,微软正式向WindowsSubsystemforLinux(WSL)用户发布了Direct3D12GPU视频加速支持。在微软通过WSL允许在Linux下使用Open...
- 《怪物猎人:崛起》曙光系统报错“Fatal d3d error”的解决办法
-
《怪物猎人:崛起》曙光系统报错“Fatald3derror”的解决办法不少小伙伴反应《怪物猎人:崛起》DLC曙光预载以后打不开游戏,出现了Fatald3derror类似的错误代码,这类问题的解...
- Mac+双屏,前端程序员的专业配置 - Loctek 乐歌 D3D 双屏电脑显示器支架
-
做FE也有一段日子了,电脑屏幕每天在设计稿、浏览器、IDE、即时通讯工具、Terminal、邮箱之间切换。虽然mac的工作区带来了很多灵活,但是依然略显不足。于是入手支架,把公司配的电脑和显示器发挥起...
- RPC 的原理和简单使用(rpc详解)
-
RPC的概念RPC,RemoteProcedureCall,翻译成中文就是远程过程调用,是一种进程间通信方式。它允许程序调用另一个地址空间(通常是共享网络的另一台机器上)的过程或函数。在调用的...
- 大厂开源的golang微服务rpc框架 — kitex
-
提前rpc估计所有的开发同学都知道,不知道的也无所谓,毕竟我也好几年没用了,今天带大家在复习一下。RPC(RemoteProcedureCall):远程过程调用,...
- 干货!一文掌握Protobuf所有语言所有用法,快收藏
-
说实话,Protobuf这个库,让人相见时难别亦难,东风无力百花残,每次等到要用它的时候,总感觉还没有完全掌握它的用法,而实际上等去百度或者谷歌的时候,教程都是多么的凌乱不堪。学会它,最直接关系到的,...
你 发表评论:
欢迎- 一周热门
- 最近发表
- 标签列表
-
- wireshark怎么抓包 (75)
- qt sleep (64)
- cs1.6指令代码大全 (55)
- factory-method (60)
- sqlite3_bind_blob (52)
- hibernate update (63)
- c++ base64 (70)
- nc 命令 (52)
- wm_close (51)
- epollin (51)
- sqlca.sqlcode (57)
- lua ipairs (60)
- tv_usec (64)
- 命令行进入文件夹 (53)
- postgresql array (57)
- statfs函数 (57)
- .project文件 (54)
- lua require (56)
- for_each (67)
- c#工厂模式 (57)
- wxsqlite3 (66)
- dmesg -c (58)
- fopen参数 (53)
- tar -zxvf -c (55)
- 速递查询 (52)