HarmonyOS 通过拍照和选择相册方式选择图片后 将图片上传到服务端

选择图片后进行上传 报错:Failed to open/read local data from file/application

其中上传的代码:

/*
* post请求上传文件
* */
export function httpUploadFileForPost(url:string , fileUrl: string) : Promise<ResponseResult>{
  // 每一个httpRequest对应一个HTTP请求任务,不可复用
  let httpRequest = http.createHttp();

  let userToken = LoginInfoTool.getInstance().userToken(false);



  let response = httpRequest.request(
    url,
    {
      method: http.RequestMethod.POST,
      header: {
        'Content-Type': 'multipart/form-data',
        'token': userToken
      },
      multiFormDataList:[{
        name: "harmonyOS_image.jpg",
        contentType: "image/jpeg",
        filePath:fileUrl
      }],
      usingCache: false,
      connectTimeout: CommonValues.CONNECT_TIME_OUT,
      readTimeout: CommonValues.CONNECT_TIME_OUT,
    }
  );

  let serverData: ResponseResult = new ResponseResult();
  Logger.info('PostUrl Request before response  ', url);


  return response.then((value: http.HttpResponse) => {
    if(value.responseCode === CommonValues.HTTP_CODE_200){

      Logger.info('PostUrl Request before response  ', url);
      serverData = value.result as ResponseResult;

      Logger.info('PostUrl Response  ', url + ' response: '+ JSON.stringify(serverData));

    }
    else{
      serverData.msg = $r('app.string.http_error_message');
      Logger.info('PostUrl Response', 'response: error');
    }
    httpRequest.destroy();
    return serverData;
  }).catch((err: Error) => {
    httpRequest.destroy();
    serverData.msg = $r('app.string.http_error_message');
    Logger.info('PostUrl Response', 'response: error');
    return serverData;
  });

}
HarmonyOS
3天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
zbw_apple

请参考下面从图库选择图片上传案例

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("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://huawei.com").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
微信
回复
3天前
相关问题
HarmonyOS 关于从相册选择图片上传
37浏览 • 1回复 待解决
进入相册拍照选择图片做头像
13629浏览 • 2回复 已解决
拉起相册选择图片页面失败
1970浏览 • 1回复 待解决