当前位置: 首页 > article >正文

鸿蒙网络编程系列21-使用HttpRequest上传任意文件到服务端示例

1. 前述文件上传功能简介

在前述文章鸿蒙网络编程系列11-使用HttpRequest上传文件到服务端示例中,为简化起见,只描述了如何上传文本类型的文件到服务端,对文件的大小也有一定的限制,只能作为鸿蒙API演示使用,在实际开发中上传的文件类型多样,大小不一,本文将介绍一种适应性更广的方法,可以上传任何类型的文件到服务端,并且不限制文件的大小。

2. 上传任意文件类型示例

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

cke_17594.jpeg

可以从图库选择文件或者选择任意文件,并且可以设置上传后的文件名,最后单击“上传”按钮即可上传到服务端。

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

步骤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:选择文件,假设单击“图库选择”按钮,弹出图片选择窗口,选择一张图片,如图所示:

cke_136630.jpeg

步骤6:单击“完成”按钮,返回APP,然后修改上传后文件名,最后单击“上传”按钮上传,如图所示:

cke_231226.jpeg

步骤7:这样就完成了图片上传,在服务端可以看到上传后的图片:

cke_489937.jpg

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

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
    }

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

本文源码地址:

https://gitee.com/zl3624/harmonyos_network_samples/tree/master/code/http/HttpRequestUploadAnyfile

本系列源码地址:

https://gitee.com/zl3624/harmonyos_network_samples


http://www.kler.cn/news/355959.html

相关文章:

  • leetcode hot100 之【LeetCode 15. 三数之和】 java实现
  • Ubuntu如何显示pcl版本
  • 【数字图像处理】第5章 图像空域增强方法
  • 【Voxceleb2-AVSpeech】视听说话人数据集云盘下载
  • 开放式耳机品牌十大排名,2024年必备开放式耳机推荐大公开!
  • 推荐系统与大语言模型技术融合:EMNLP/NeurIPS相关论文导览
  • 计算机砖头书的学习建议
  • 【优选算法】探索双指针之美(一):初识双指针
  • opencv实时采集图像作为opengl的纹理贴图
  • 机器人学 目录
  • Spring 的依赖注入的最常见方式
  • Qt与下位机通信时,如何等待下位机回复和超时处理
  • [IOI2018] werewolf 狼人(Kruskal重构树 + 主席树)
  • 高级交换基础
  • day48 图论章节刷题Part01(深搜理论基础、98. 所有可达路径、广搜理论基础)
  • Elixir 工具篇
  • Flink PostgreSQL CDC源码解读:深入理解数据流同步
  • Android一代整体壳简易实现和踩坑记录
  • Linux Ubuntu dbus CAPI ---- #include<dbus.h>出现“无法打开源文件dbus/xxx.h“的问题
  • 数据结构-5.8.由遍历序列构造二叉树