HarmonyOS 鸿蒙Next中如何发送form-data数据

HarmonyOS 鸿蒙Next中如何发送form-data数据 问AI,AI跟智障一样,老是生成不存在的接口!

后端需要form-data

async function sendRequest(request: CreateRequest, token: string):Promise<CommonDetailsResponse<BasicInfoModel>> {
  // 判断文件后缀
  let fileExtension:string = request.imageUrl.substring(request.imageUrl.lastIndexOf('.') + 1).toLowerCase();
  let mimeType:string = '';
  switch (fileExtension) {
    case 'jpg':
    case 'jpeg':
      mimeType = 'image/jpeg';
      break;
    case 'png':
      mimeType = 'image/png';
      break;
    case 'webp':
      mimeType = 'image/webp';
      break;
    default:
      mimeType = 'image/jpeg';
  }

  //创建请求
  let httpRequest = http.createHttp();
  

  return httpRequest.request("https://xxx",
    {
      method: http.RequestMethod.POST,
      header: {
        'Accept': 'application/json',
        'Authorization': 'Bearer ' + token,
        'User-Agent': CommonUtil.userAgent
      },
      extraData: {
        multiFormDataList: [
          { name: "Name", data: request.toName },
          { name: "PhoneNumber", data: request.toPhoneNumber },
          { name: "EMail", data: request.toEMail },
          { name: "TextContent", data: request.textContent },
          { name: "ImageFile", contentType: mimeType, filePath: request.imageUrl }
        ]
      }
    }
  ).then((data: http.HttpResponse) => {
    hilog.debug(0x0001, TAG, data.result.toString());
    // 严格判断成功状态码
    if (data.responseCode !== http.ResponseCode.OK) { // 精确匹配200状态码
      const errorMessage = data.result?.toString() || `HTTP ${data.responseCode}`;
      return Promise.reject(errorMessage);
    }
    // 成功状态下处理JSON
    const responseText = data.result.toString();
    const jsonData = JSON.parse(responseText);
    return jsonData as CommonDetailsResponse<BasicInfoModel>;
  }).catch((error:BusinessError) => {
    // 错误处理
    hilog.error(0x0002, TAG, 'error:' + error);
    return Promise.reject(error);
  }).finally(() => {
    httpRequest.destroy();// 销毁请求
  });
}

更多关于HarmonyOS 鸿蒙Next中如何发送form-data数据的实战教程也可以访问 https://www.itying.com/category-93-b0.html

3 回复

可以使用multiFormDataList提交formdata,指导文档:https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-http-V5

调用httpRequest能力,将文件流上传到服务器,示例代码如下:

static async upload<T>(url: string, buffer: ArrayBuffer) {
  let httpRequest = http.createHttp();
  httpRequest.request(url,
    {
      method: http.RequestMethod.POST, // 可选,默认为http.RequestMethod.GET。
      // 当使用POST请求时此字段用于传递请求体内容,具体格式与服务端协商确定。
      multiFormDataList: [{
        name: 'file',
        contentType: 'image/png',
        data: buffer,
        remoteFileName: 'text.png'              // 注意如果为流上传文件,则此处为必填项
      }],
      expectDataType: http.HttpDataType.STRING, // 可选,指定返回数据的类型。
      usingCache: true,                         // 可选,默认为true。
      priority: 1,                              // 可选,默认为1。
      // 开发者根据自身业务需要添加header字段。
      header: {
        'content-type': 'multipart/form-data'
      },
      readTimeout: 60000,                         // 可选,默认为60000ms。
      connectTimeout: 60000,                      // 可选,默认为60000ms。
      usingProtocol: http.HttpProtocol.HTTP1_1,   // 可选,协议类型默认值由系统自动指定。
      usingProxy: false,                          // 可选,默认不使用网络代理,自API 10开始支持该属性。
    },
    (err: BusinessError, data: http.HttpResponse) => {
      if (err) {
        console.error('http client request error:' , JSON.stringify(err));
        httpRequest.off('headersReceive');
        httpRequest.destroy();
        return;
      }

      try {
        console.info('http client response info:' , data.result.toString());
        httpRequest.destroy();
      } catch (parseError) {
        httpRequest.destroy();
      }
    }
  );
}

更多详细使用方法可以参考官网文档[@ohos.net.http (数据请求)](https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-http-V5#完整示例)

【背景知识】

[@ohos.net.http (数据请求)](https://developer.huawei.com/consumer/cn/doc/harmonyos-references/js-apis-http):本模块提供HTTP数据请求能力。应用可以通过HTTP发起一个数据请求,支持常见的GET、POST、OPTIONS、HEAD、PUT、DELETE、TRACE、CONNECT方法。

更多关于HarmonyOS 鸿蒙Next中如何发送form-data数据的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中发送form-data数据,需使用@ohos.net.http模块的HttpRequest类。创建FormData对象,通过append()方法添加键值对或文件数据。配置请求选项,将formData属性设为该对象,并设置请求方法为POST。调用request()方法发送请求。示例代码:

import http from '@ohos.net.http';

let formData = new http.FormData();
formData.append('key', 'value');
// 添加文件:formData.append('file', fileObject, 'filename.txt');

let options = {
  method: http.RequestMethod.POST,
  formData: formData
};
http.request(url, options, (err, data) => {});

在HarmonyOS Next中,使用@ohos.net.http模块发送form-data数据时,你的代码基本正确,但需要注意几个关键点:

  1. Content-Type设置:发送multipart/form-data时,系统会自动设置正确的Content-Type,无需手动添加。但需要确保extraData中的multiFormDataList结构正确。

  2. 文件上传处理:你处理图片MIME类型的方式是正确的,但建议增加文件存在性检查:

import fs from '@ohos.file.fs';
// 在读取文件前添加检查
try {
  let file = fs.openSync(request.imageUrl, fs.OpenMode.READ_ONLY);
  fs.closeSync(file);
} catch (error) {
  return Promise.reject('文件不存在或无法访问');
}
  1. 参数格式:multiFormDataList中的字段定义准确,包含文本字段和文件字段的混合。

  2. 错误处理:你现有的错误处理逻辑完善,包含了HTTP状态码检查和异常捕获。

当前代码已经实现了标准的form-data上传功能,包括:

  • 多部分表单数据构造
  • 文件MIME类型自动识别
  • 授权令牌传递
  • 完整的Promise链式处理

如果遇到具体问题,可能是网络权限未配置或文件路径不正确导致的。

回到顶部