HarmonyOS 使用@ohos.net.http \(数据请求\)如何进行图片上传?

如题:HarmonyOS 使用@ohos.net.http (数据请求)如何进行图片上传?

阅读 406
1 个回答

示例参考:

import { BusinessError } from '@ohos.base';
import { rcp } from '@kit.RemoteCommunicationKit';
import { picker } from '@kit.CoreFileKit';
import fs from '@ohos.file.fs';
import { http } from '@kit.NetworkKit';

let uploadUrl: string = 'http://huawei.com';


function example01(): string {
  let uri = '';
  let photoViewPicker = new picker.PhotoViewPicker();
  let photoSelectOption = new picker.PhotoSelectOptions();
  photoSelectOption.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
  photoViewPicker.select(photoSelectOption).then((photoSelectResult) => {
    console.log("photoSelectResult:" + photoSelectResult);
    uri = photoSelectResult.photoUris[0];
    console.log("uri:" + uri);
    try {
      let resultPhoto = fs.openSync(uri, fs.OpenMode.READ_ONLY);
      let resultName = resultPhoto.name;
      let fileTemp = fs.openSync(getContext().filesDir + resultPhoto.name, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
      let imageUri = fileTemp.path;
      console.log('上传uri' + imageUri);
      fs.copyFileSync(resultPhoto.fd, fileTemp.fd);
      fs.closeSync(resultPhoto);
      fs.closeSync(fileTemp);
      const httpRequest = http.createHttp();
      httpRequest.request(uploadUrl, {
        method: http.RequestMethod.POST,
        header: {
          'Content-Type': 'multipart/form-data',
          'Connection': 'keep-alive'
        },
        expectDataType: http.HttpDataType.ARRAY_BUFFER,
        multiFormDataList: [
          {
            name: 'file',
            contentType: 'image/jpg',
            filePath: imageUri,
            remoteFileName: 'file.jpg'
          },
        ],
      }, (err, data) => {
        console.log('上传结束')
        httpRequest.destroy();
      }
      )
    } catch (err) {
      console.log('上传失败')
      console.error(`Failed to request the upload. err: ${JSON.stringify(err)}`);
    }

  }).catch((err: BusinessError) => {
    console.log('上传失败')
    console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  })
  return uri;
}


function testRcpMultiPartUpload() {
  example01();
}


@Entry
@Component
struct Index {
  @State message: string = '上传图片';

  build() {
    Row() {
      Column() {
        Text(this.message)
          .fontSize(50)
          .fontWeight(FontWeight.Bold)
          .onClick(() => {
            testRcpMultiPartUpload();
          })

      }
      .width('100%')
    }
    .height('100%')
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
HarmonyOS
子站问答
访问
宣传栏