HarmonyOS 选择图片上传到服务器的demo

HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
put_get
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://192.168.62.4:8080/upload';

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("tag photoSelectResult:" + photoSelectResult);
    uri = photoSelectResult.photoUris[0];
    console.log("tag 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;
      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('tag:上传结束')
        httpRequest.destroy();
      })
    } catch (err) {
      console.error(`tag:Failed to request the upload. err: ${JSON.stringify(err)}`);
    }
  }).catch((err: BusinessError) => {
    console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
  })
  return uri;
}

function testRcpMultiPartUpload() {
  example01();
}

function clickget() {
  const session = rcp.createSession();
  session.get("http://192.168.xx.4:8080/getText").then((response) => {
    console.log("tag" + JSON.stringify(response));
  }).catch((err: BusinessError) => {
    console.error("err:" + JSON.stringify(err));
  });
}

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

  build() {
    Row() {
      Column() {
        Text(this.message).fontSize(50).fontWeight(FontWeight.Bold).onClick(() => {
          testRcpMultiPartUpload();
        })
        Text('getText').fontSize(50).fontWeight(FontWeight.Bold).onClick(() => {
          clickget();
        })
      }.width('100%')
    }.height('100%')
  }
}
分享
微博
QQ
微信
回复
1天前
相关问题
HarmonyOS 文件上传服务器问题
397浏览 • 1回复 待解决
HarmonyOS Rcp.post上传图库文件至服务器
336浏览 • 1回复 待解决
请求服务器图片资源刷新卡片
932浏览 • 1回复 待解决