鸿蒙开发系列(HarmonyOS)通过HttpRequest上传文件到服务端实践

鸿蒙NEXT开发实战往期必看文章:

一分钟了解”纯血版!鸿蒙HarmonyOS Next应用开发!

“非常详细的” 鸿蒙HarmonyOS Next应用开发学习路线!(从零基础入门到精通)

HarmonyOS NEXT应用开发案例实践总结合(持续更新......)

HarmonyOS NEXT应用开发性能优化实践总结(持续更新......)


1. HTTP上传文件简介

在上一篇文章使用HttpRequest下载文件到本地示例中,我们使用HttpRequest下载了文件,同样,使用HttpRequest也可以上传文件,假设我们有一个网站,其文件上传地址为http://192.168.100.101:8081/upload,为简单起见,该网站不需要登录既可以上传文件,当然,需要的登录话也没什么,参考上一篇文章即可。本文将模拟文件上传的功能,开发鸿蒙应用客户端把文件上传到服务端,为减少复杂性,假设上传的是文本类型的小文件,其他类型的或者更大的文件,也可以参考本文修改。

2. 客户端上传示例

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

0900086000300134184.20201216095126.86523331460016843504112994983392.png

单击选择按钮,从本地选择文件后,然后单击上传按钮即可上传文件到服务端。

下面详细介绍创建该应用的步骤。

步骤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';

@Entry
@Component
struct Index {
  //连接、通讯历史记录
  @State msgHistory: string = ''
  //上传地址
  @State uploadUrl: string = "http://192.168.100.101:8081/upload"
  //要上传的文件
  @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)

          Button("选择")
            .onClick(() => {
              this.selectFile()
            })
            .width(70)
            .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)

          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: string) {
    let body = `--${boundary}\r\n`
    body = body + `Content-Disposition: form-data; name="file"; filename="${fileName}"\r\n`
    body = body + `Content-Type: text/plain\r\n`
    body = body + '\r\n'
    body = body + content
    body = body + '\r\n'
    body = body + `--${boundary}`
    body = body + '--\r\n'
    return body
  }

  //上传文件
  async uploadFile() {
    //上传文件使用的分隔符
    let boundary: string = '----ShandongCaoxianNB666MyBabyBoundary' + (await systemDateTime.getCurrentTime(true)).toString()

    //选择要上传的文件的内容
    let fileContent: string = buf2String(this.readContentFromFile(this.uploadFilePath))

    let segments = this.uploadFilePath.split('/')
    //文件名称
    let fileName = segments[segments.length-1]

    //上传请求的body内容
    let bodyContent = this.buildBodyContent(boundary, fileName, fileContent)
    let textEncoder = new util.TextEncoder();
    let contentBuf = textEncoder.encodeInto(bodyContent)

    //http请求对象
    let httpRequest = http.createHttp();
    let opt: http.HttpRequestOptions = {
      method: http.RequestMethod.POST,
      header: { 'Content-Type': `multipart/form-data; boundary=${boundary}`,
        'Content-Length': contentBuf.length.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"
      })
  }

  //选择文件,为简单起见,选择一个不太大的文本文件
  selectFile() {
    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
      }
    }).catch((e) => {
      this.msgHistory += 'DocumentViewPicker.select failed ' + e.message + "\r\n";
    });
  }

  //从文件读取内容
  readContentFromFile(fileUri: string): ArrayBuffer {
    let buf = new ArrayBuffer(1024 * 4);
    let file = fs.openSync(fileUri, fs.OpenMode.READ_ONLY);
    let readLen = fs.readSync(file.fd, buf, { offset: 0 });
    let result = buf.slice(0, readLen)
    fs.closeSync(file);
    return result
  }
}

//ArrayBuffer转utf8字符串
function buf2String(buf: ArrayBuffer) {
  let msgArray = new Uint8Array(buf);
  let textDecoder = util.TextDecoder.create("utf-8");
  return textDecoder.decodeWithStream(msgArray)
}

步骤4:编译运行,可以使用模拟器或者真机。

步骤5:单击“选择”按钮,弹出文件选择窗口,如图所示:。

0900086000300134184.20201216095126.86523331460016843504112994983392.png

步骤6:选择要上传的文件,这里选择"harmonyos.txt",返回应用后的截图如下所示:

0900086000300134184.20201216095126.86523331460016843504112994983392.png

因为鸿蒙系统对物理文件和沙箱文件作了隔离,在应用看来,这个文件的路径是file: datashare:///media/file/482909

步骤7:单击“上传”按钮,上传文件到服务端,截图如下所示:

0900086000300134184.20201216095126.86523331460016843504112994983392.png

步骤8:在服务端可以看到上传后的文件(具体路径和服务端有关):

0900086000300134184.20201216095126.86523331460016843504112994983392.png

使用记事本打开该文件,可以看到文件内容:

0900086000300134184.20201216095126.86523331460016843504112994983392.png

这样就完成了文件的上传。

3. 上传功能分析

要实现上传功能,关键点在如下方面:

首先,构造HTTP请求的body部分,代码如下:

  //构造上传文本文件的body内容
  buildBodyContent(boundary: string, fileName: string, content: string) {
    let body = `--${boundary}\r\n`
    body = body + `Content-Disposition: form-data; name="file"; filename="${fileName}"\r\n`
    body = body + `Content-Type: text/plain\r\n`
    body = body + '\r\n'
    body = body + content
    body = body + '\r\n'
    body = body + `--${boundary}`
    body = body + '--\r\n'
    return body
  }

特别注意的是Content-Disposition和Content-Type,另外就是参数boundary,它是分隔符,要保证不和文件内容重复。

其次,就是请求的Header部分,代码如下:

    //http请求对象
    let httpRequest = http.createHttp();
    let opt: http.HttpRequestOptions = {
      method: http.RequestMethod.POST,
      header: { 'Content-Type': `multipart/form-data; boundary=${boundary}`,
        'Content-Length': contentBuf.length.toString()
      },
      extraData: bodyContent
    }

比较容易犯错的是Content-Length,它是内容的字节长度。

<think>我们正在开发鸿蒙HarmonyOS Next应用,需要使用HTTP工具类。根据引用内容,鸿蒙API内置了HTTP客户端支持(HttpRequest),但暂不支持HTTP服务端(不过可以通过TCP Server自行实现)。用户的需求是获取HTTP工具类的开发使用方法和示例代码。 根据引用[1]和引用[3],我们可以知道: 1. 鸿蒙提供了HttpRequest类用于HTTP客户端请求。 2. 引用[3]中提供了一个示例工程结构,并提到在http.ts文件中封装了http参数和发起请求的接口。 因此,我们将重点介绍如何使用HttpRequest类发起HTTP请求,并提供一个简单的示例代码。 步骤: 1. 配置权限:在config.json中声明网络权限。 2. 导入模块:在代码中导入http模块。 3. 创建HttpRequest对象。 4. 设置请求参数(URL、方法、头部、响应类型等)。 5. 发起请求并处理响应。 注意:鸿蒙的HTTP请求是异步的,我们可以使用Promise或者回调函数来处理响应。 示例代码(TypeScript): 以下是一个简单的GET请求示例,以及一个POST请求示例。 首先,确保在config.json中声明网络权限: ```json { "module": { "reqPermissions": [ { "name": "ohos.permission.INTERNET" } ] } } ``` 然后,在代码中: ```typescript import http from '@ohos.net.http'; // 创建HttpRequest对象 let httpRequest = http.createHttp(); // 示例1:GET请求 async function httpGet() { let url = 'https://example.com/api/get'; try { let response = await httpRequest.request( url, { method: http.RequestMethod.GET, header: { 'Content-Type': 'application/json' } } ); // 请求成功,response.result为响应体 console.log('GET Result: ' + JSON.stringify(response.result)); console.log('GET Code: ' + response.responseCode); } catch (error) { console.error('GET Error: ' + JSON.stringify(error)); } } // 示例2:POST请求 async function httpPost() { let url = 'https://example.com/api/post'; try { let response = await httpRequest.request( url, { method: http.RequestMethod.POST, header: { 'Content-Type': 'application/json' }, extraData: { key1: 'value1', key2: 'value2' } } ); console.log('POST Result: ' + JSON.stringify(response.result)); console.log('POST Code: ' + response.responseCode); } catch (error) { console.error('POST Error: ' + JSON.stringify(error)); } } ``` 说明: 1. 使用`http.createHttp()`创建一个HttpRequest实例。 2. 调用`request`方法发起请求,第一个参数是URL,第二个参数是配置对象,包括: - method: 请求方法(GET, POST等) - header: 请求头 - extraData: 请求体(POST请求时使用) 3. 使用async/await处理异步请求,也可以使用回调函数(通过配置对象中的readable和writable属性,但推荐使用Promise方式)。 注意:在实际开发中,建议将HTTP请求封装成工具类,以便复用和管理。 封装示例(参考引用[3]中的http.ts): 我们可以创建一个HttpUtil类,封装GET和POST方法。 http.ts: ```typescript import http from '@ohos.net.http'; export default class HttpUtil { private httpRequest: http.HttpRequest; constructor() { this.httpRequest = http.createHttp(); } // GET请求 async get(url: string, headers: Object = {}): Promise<any> { try { let response = await this.httpRequest.request(url, { method: http.RequestMethod.GET, header: headers }); return response.result; } catch (error) { console.error('HttpUtil GET Error: ' + JSON.stringify(error)); throw error; } } // POST请求 async post(url: string, data: Object, headers: Object = {'Content-Type': 'application/json'}): Promise<any> { try { let response = await this.httpRequest.request(url, { method: http.RequestMethod.POST, header: headers, extraData: data }); return response.result; } catch (error) { console.error('HttpUtil POST Error: ' + JSON.stringify(error)); throw error; } } } ``` 使用封装好的工具类: ```typescript import HttpUtil from './HttpUtil'; // 在页面中 let httpUtil = new HttpUtil(); // 发送GET请求 httpUtil.get('https://example.com/api/get').then(result => { console.log('Result: ' + JSON.stringify(result)); }).catch(error => { console.error('Error: ' + JSON.stringify(error)); }); // 发送POST请求 let data = { key: 'value' }; httpUtil.post('https://example.com/api/post', data).then(result => { console.log('Result: ' + JSON.stringify(result)); }).catch(error => { console.error('Error: ' + JSON.stringify(error)); }); ``` 注意事项: 1. 确保设备有网络连接。 2. 注意异步处理,避免阻塞UI。 3. 错误处理要完善。 以上就是在鸿蒙HarmonyOS Next中使用HTTP工具类的基本方法和示例代码。 根据用户需求,我们提供了开发步骤、示例代码以及封装工具类的建议。用户可以根据实际需求调整封装类。 §§相关问题§§ 1. 鸿蒙HarmonyOS Next中如何处理HTTPS请求? 2. 如何设置HTTP请求的超时时间? 3. 鸿蒙HTTP请求支持哪些方法? 4. 如何上传文件?</think>### 鸿蒙 HarmonyOS Next HTTP 工具类开发指南 #### 一、开发准备 1. **权限声明** 在 `module.json5` 中添加网络权限: ```json "requestPermissions": [ { "name": "ohos.permission.INTERNET" } ] ``` 2. **依赖导入** 在代码中导入 HTTP 模块: ```typescript import http from '@ohos.net.http'; ``` #### 二、核心工具类封装 ```typescript // HttpUtil.ts export default class HttpUtil { private httpRequest: http.HttpRequest; constructor() { this.httpRequest = http.createHttp(); } // GET请求 async get(url: string, params?: Record<string, string>): Promise<any> { const fullUrl = params ? `${url}?${new URLSearchParams(params)}` : url; return this.request(fullUrl, http.RequestMethod.GET); } // POST请求 async post(url: string, data: object): Promise<any> { return this.request(url, http.RequestMethod.POST, data); } // 统一请求方法 private async request( url: string, method: http.RequestMethod, data?: object ): Promise<any> { try { const response = await this.httpRequest.request(url, { method, header: { 'Content-Type': 'application/json' }, extraData: data ? JSON.stringify(data) : undefined }); if (response.responseCode === http.ResponseCode.OK) { return JSON.parse(response.result.toString()); } else { throw new Error(`HTTP Error ${response.responseCode}`); } } catch (error) { console.error(`Request failed: ${JSON.stringify(error)}`); throw error; } } } ``` #### 三、使用示例 ```typescript // MainPage.ets import HttpUtil from './HttpUtil'; @Entry @Component struct MainPage { private http: HttpUtil = new HttpUtil(); async fetchData() { try { // GET示例 const userData = await this.http.get( 'https://api.example.com/users', { id: '123' } ); // POST示例 const loginRes = await this.http.post( 'https://api.example.com/login', { username: 'test', password: '123456' } ); console.log('Login response:', loginRes); } catch (error) { console.error('API Error:', error); } } build() { Column() { Button('获取数据') .onClick(() => this.fetchData()) } } } ``` #### 四、关键功能说明 1. **请求方法支持** - 支持所有标准方法:`GET`, `POST`, `PUT`, `DELETE` 等 - 通过 `http.RequestMethod` 枚举调用 2. **参数处理**: - GET 参数自动 URL 编码 - POST 数据自动 JSON 序列化 3. **错误处理**: - 自动捕获网络异常 - 验证 HTTP 状态码(200-299 视为成功) 4. **响应处理**: - 自动将响应体解析为 JSON 对象 - 原始数据可通过 `response.result` 获取 #### 五、进阶配置 ```typescript // 自定义请求示例 const customRequest = await httpRequest.request( 'https://api.example.com/upload', { method: http.RequestMethod.PUT, header: { 'Authorization': 'Bearer token', 'Custom-Header': 'value' }, connectTimeout: 30_000, // 30秒超时 usingCache: true // 启用缓存 } ); ``` > **注意事项**: > 1. 鸿蒙 NEXT 的 HTTP 客户端**不支持服务端开发**,需通过 `TCPSocketServer` 自行实现 [^2] > 2. 使用 HTTPS 需配置网络安全策略 > 3. 文件上传需使用 `@ohos.multimedia.mediaLibrary` 模块
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值