HarmonyOS 包含文件提交的表单提交示例?

需要一个代码示例,有关提交表单的,且表单中可以包含文件,具体代码应该怎么写

阅读 500
1 个回答

可以参考以下链接

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/remote-communication-rcp-V5

https://developer.huawei.com/consumer/cn/doc/harmonyos-releases-V5/js-apidiff-remotecommunicationkit-hdc-V5

import { BusinessError } from '@ohos.base';
import { hilog } from '@kit.PerformanceAnalysisKit';
import { rcp } from '@kit.RemoteCommunicationKit';
import { util } from '@kit.ArkTS';

let encoder = new util.TextEncoder();
let uploadUrl: string = 'http://192.168.71.9:8080/upload';

function testRcpMultiPartUpload(): void {
  let multiFormFieldValue1 = buildMultipartFormFieldValue('1.txt', '111', 'text/plain');
  let multiFormFieldValue2 = buildMultipartFormFieldValue('2.txt', '222', 'text/plain');
  let headers: rcp.RequestHeaders = {
    "content-type": 'multipart/form-data'
  };
  const session = rcp.createSession();
  const multiForm = new rcp.MultipartForm({
    file: [multiFormFieldValue1, multiFormFieldValue2]
  });
  let req = new rcp.Request(uploadUrl, "POST", headers, multiForm);
  session.fetch(req).then((response) => {
    hilog.info(0x0000, 'testTag', 'success %{public}s', JSON.stringify(response));
  }).catch((err: BusinessError) => {
    hilog.info(0x0000, 'testTag', 'error %{public}s', "err:" + JSON.stringify(err));
  }).finally(() => {
    session.close();
  });
}

function buildMultipartFormFieldValue(fileName: string, content: string, contentType: string): rcp.MultipartFormFieldValue {
  let result: rcp.MultipartFormFieldValue = {
    remoteFileName: fileName,
    contentOrPath: {
      content: encoder.encodeInto(content).buffer
    },
    contentType: contentType
  }
  return result;
}

@Entry
@Component
struct Index {
  @State message: string = 'Hello World';

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            testRcpMultiPartUpload();
          })
      }
      .width('100%')
    }
    .height('100%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进