HarmonyOS 文件上传RemoteCommunicationKit+FROM表单+POST?

使用RemoteCommunicationKit实现,FROM表单+POST上传文件报错:

{"code":1007900026,"data":"Failed to open/read local data from file/application"}

操作步骤:

1、上传头像,打开系统相机或相册选择图片。

2、上传到服务器。

代码逻辑步骤:

1、定义权限,module.json5中添加权限声明:

//允许应用获取网络权限
{
  "name": "ohos.permission.INTERNET",
  "usedScene": {
    "abilities": [
      "FormAbility"
    ],
    "when": "inuse"
  }
},
//允许应用使用相机权限
{
  "name": "ohos.permission.CAMERA",
  "reason": "$string:permission_camera_reason",
  "usedScene": {
    "abilities": [
      "EntryAbility"
    ]
  }
},
// 用于应用读取用户外部储存中的媒体文件信息
{
  "name": "ohos.permission.READ_MEDIA",
  "reason": "$string:permission_readMedia_reason",
  "usedScene": {
    "abilities": [
      "EntryAbility"
    ]
  }
},
// 用于应用写入用户外部储存中的媒体文件信息
{
  "name": "ohos.permission.WRITE_MEDIA",
  "reason": "$string:permission_writeMedia_reason",
  "usedScene": {
    "abilities": [
      "EntryAbility"
    ]
  }
}

2、从相册选择文件并得到文件路径:file://media/Photo/8/IMG\_1720688648\_002/tz.jpg(验证地址是否准确,使用Image加载该路径,可正常展示)。

3、发送请求上传文件。

阅读 378
1 个回答

相册路径不能直接用于传输,可以通过将相册图片复制到应用沙箱路径下,然后再用沙箱路径下的文件进行传输。从相册复制文件到沙箱目录,可参考如下代码:

function SavePhotoToFileDir() {
  try {
    let photoSelectOptions = new picker.PhotoSelectOptions();
    photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
    photoSelectOptions.maxSelectNumber = 1;
    let photoPicker = new picker.PhotoViewPicker();
    let uris: Array<string> = [];
    photoPicker.select(photoSelectOptions).then((photoSelectResult: picker.PhotoSelectResult) => {
      uris = photoSelectResult.photoUris;
      let fileArray = uris[0].split("/");
      let fileName = fileArray[fileArray.length - 1];
      let file = fs.openSync(uris[0], fs.OpenMode.READ_ONLY);
      let cacheDir = mContext.filesDir;
      let dstPath = cacheDir + '/' + fileName;
      let file2 = fs.openSync(dstPath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
      fs.copyFileSync(file.fd, file2.fd);
      fs.closeSync(file);
      console.info('PhotoViewPicker.select successfully, photoSelectResult uri: ' + JSON.stringify(photoSelectResult));
    }).catch((err: BusinessError) => {
      console.error('PhotoViewPicker.select failed with err: ' + JSON.stringify(err));
    });
  } catch (error) {
    let err: BusinessError = error as BusinessError;
    console.error('PhotoViewPicker failed with err: ' + JSON.stringify(err));
  }
}
logo
HarmonyOS
子站问答
访问
宣传栏