百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术分析 > 正文

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

liebian365 2024-11-09 13:44 30 浏览 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

本系列源码地址:

HarmonyOSNetworkSamples: 鸿蒙网络编程示例仓库

相关推荐

4万多吨豪华游轮遇险 竟是因为这个原因……

(观察者网讯)4.7万吨豪华游轮搁浅,竟是因为油量太低?据观察者网此前报道,挪威游轮“维京天空”号上周六(23日)在挪威近海发生引擎故障搁浅。船上载有1300多人,其中28人受伤住院。经过数天的调...

“菜鸟黑客”必用兵器之“渗透测试篇二”

"菜鸟黑客"必用兵器之"渗透测试篇二"上篇文章主要针对伙伴们对"渗透测试"应该如何学习?"渗透测试"的基本流程?本篇文章继续上次的分享,接着介绍一下黑客们常用的渗透测试工具有哪些?以及用实验环境让大家...

科幻春晚丨《震动羽翼说“Hello”》两万年星间飞行,探测器对地球的最终告白

作者|藤井太洋译者|祝力新【编者按】2021年科幻春晚的最后一篇小说,来自大家喜爱的日本科幻作家藤井太洋。小说将视角放在一颗太空探测器上,延续了他一贯的浪漫风格。...

麦子陪你做作业(二):KEGG通路数据库的正确打开姿势

作者:麦子KEGG是通路数据库中最庞大的,涵盖基因组网络信息,主要注释基因的功能和调控关系。当我们选到了合适的候选分子,单变量研究也已做完,接着研究机制的时便可使用到它。你需要了解你的分子目前已有哪些...

知存科技王绍迪:突破存储墙瓶颈,详解存算一体架构优势

智东西(公众号:zhidxcom)编辑|韦世玮智东西6月5日消息,近日,在落幕不久的GTIC2021嵌入式AI创新峰会上,知存科技CEO王绍迪博士以《存算一体AI芯片:AIoT设备的算力新选择》...

每日新闻播报(September 14)_每日新闻播报英文

AnOscarstatuestandscoveredwithplasticduringpreparationsleadinguptothe87thAcademyAward...

香港新巴城巴开放实时到站数据 供科技界研发使用

中新网3月22日电据香港《明报》报道,香港特区政府致力推动智慧城市,鼓励公私营机构开放数据,以便科技界研发使用。香港运输署21日与新巴及城巴(两巴)公司签署谅解备忘录,两巴将于2019年第3季度,开...

5款不容错过的APP: Red Bull Alert,Flipagram,WifiMapper

本周有不少非常出色的app推出,鸵鸟电台做了一个小合集。亮相本周榜单的有WifiMapper's安卓版的app,其中包含了RedBull的一款新型闹钟,还有一款可爱的怪物主题益智游戏。一起来看看我...

Qt动画效果展示_qt显示图片

今天在这篇博文中,主要实践Qt动画,做一个实例来讲解Qt动画使用,其界面如下图所示(由于没有录制为gif动画图片,所以请各位下载查看效果):该程序使用应用程序单窗口,主窗口继承于QMainWindow...

如何从0到1设计实现一门自己的脚本语言

作者:dong...

三年级语文上册 仿写句子 需要的直接下载打印吧

描写秋天的好句好段1.秋天来了,山野变成了美丽的图画。苹果露出红红的脸庞,梨树挂起金黄的灯笼,高粱举起了燃烧的火把。大雁在天空一会儿写“人”字,一会儿写“一”字。2.花园里,菊花争奇斗艳,红的似火,粉...

C++|那些一看就很简洁、优雅、经典的小代码段

目录0等概率随机洗牌:1大小写转换2字符串复制...

二年级上册语文必考句子仿写,家长打印,孩子照着练

二年级上册语文必考句子仿写,家长打印,孩子照着练。具体如下:...

一年级语文上 句子专项练习(可打印)

...

亲自上阵!C++ 大佬深度“剧透”:C++26 将如何在代码生成上对抗 Rust?

...

取消回复欢迎 发表评论: