HarmonyOS system.request 怎么传输formData格式的file对象

后台接口需要传输multipart/form-data 格式数据,经过PhotoViewPicker后拿到的图片路径,但是后台接口需要file对象。前端代码如下:

const formData = new FormData()
formData.append('file',e.file)
formData.append('fileName', e.fileName)
  • 1.
  • 2.
  • 3.
private openGalleryInternal() {
  let photoPicker = new picker.PhotoViewPicker();
  photoPicker.select({
    MIMEType: picker.PhotoViewMIMETypes.IMAGE_TYPE,
    maxSelectNumber: 1
  }, (error, result) => {
    if (result) {
      this.uploadImage(result.photoUris);
      LogUtil.error(this.TAG, '')
      result.photoUris.forEach((url) => {
        console.log("url: " + url);
      })
    }
  });
}

private uploadImage(paths: string[]) {
  const allFiles = Array<request.File>()
  for (let i = 0; i <paths.length; i++) {
    let path = paths[i]
    console.log("path: " + path)
    allFiles[i] = {
      name: "image" + i + ".jpg",
      filename: "image" + i + ".jpg",
      uri: path,
      type: "jpg"
    }
  }

  request.uploadFile(getContext(this), {
    url: API_LIST.files,
    method: "POST",
    files: allFiles,
    header: {
      'content-type': 'multipart/from-data;boundary=----WebKitFormBoundaryn8D9asOnAnEU4Js0',
    },
    data: [
      {
        name: "fileName",
        value: 'ceshi'
      },
      {
        name: "file",
        value:  这里应该传输一个file对象
      },
      {
        name: "appId",
        value: signHead.headData.appId
      },
      {
        name: "uid",
        value: signHead.headData.uid
      },
      {
        name: "token",
        value: signHead.headData.token
      },
      {
        name: "deviceType",
        value: signHead.headData.deviceType
      }
    ]
  }, (error, response) => {
    if(response) {
      response.on('progress', (uploadedSize: number, totalSize: number) => {
        console.log("progress, uploadedSize: " + uploadedSize + ", totalSize: " + totalSize)
      })
    } else {
      console.log("upload failure: " + error)
    }
  });
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
HarmonyOS
2024-12-23 15:13:29
浏览
收藏 0
回答 1
回答 1
按赞同
/
按时间
shlp

通过PhotoViewPicker获取到的图片不能直接用于传输,可以通过将其复制在应用沙箱路径下,然后再用沙箱路径下的文件进行传输。 下面是部分demo:

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;
      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.error(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://huawei.com").then((response) => {
    console.log(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%')
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
分享
微博
QQ
微信
回复
2024-12-23 19:24:02
相关问题
HarmonyOS 有没有对应Java语言File对象
566浏览 • 1回复 待解决
HarmonyOS Sendable装饰对象怎么获取
688浏览 • 1回复 待解决
HarmonyOS 对象怎么判空?
1848浏览 • 1回复 待解决
HarmonyOS 怎么获取VpnExtensionContext对象
434浏览 • 1回复 待解决