HarmonyOS 使用 @ohos.request 进行图片上传,如何能接受到自定义的 response?

在 APP 中需要上传肖像,上传成功后,后台会给出上传后的信息,如下所示:

{
  "code": 200,
  "msg": "成功",
  "data": {
    "result": {
      "number": 1,
      "url": "https://xxx.jpg"
    },
  "message": "文件上传成功",
  "status": 1
  }
}

而在request.uploadFile的 then 方法中,只能拿到 uploadTask 或 TaskState的数据:

// 将本地应用文件上传至网络服务器
try {
  request.uploadFile(context, uploadConfig)
    .then((uploadTask: request.UploadTask) => {
      uploadTask.on('complete', (taskStates: Array<request.TaskState>) => {
        for (let i = 0; i < taskStates.length; i++) {
          console.info(`upload complete taskState: ${JSON.stringify(taskStates[i])}`);
        }
      });
    })
    .catch((err: BusinessError) => {
      console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
    })
} catch (error) {
  let err: BusinessError = error as BusinessError;
  console.error(`Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
}

我怎么才能拿到后台返给我的数据呢?

阅读 526
1 个回答

可以尝试下如下方法:

try {
  request.uploadFile(getContext(), uploadConfig).then((data: request.UploadTask) => {
    let uploadTask = data;
    uploadTask.on('complete', (taskStates: Array<request.TaskState>) => {
      for (let i = 0; i < taskStates.length; i++) {
        console.info(`upload complete taskState: ${JSON.stringify(taskStates[i])}`);
      }
    });
    uploadTask.on('headerReceive', (header: Object) => {
      console.log('###headerReceive', JSON.stringify(header))
      if (header) {
        let body: object = JSON.parse(JSON.stringify(header)).body
        console.log('=====body', JSON.stringify(body))
      }
    })
  }).catch((err: BusinessError) => {
    console.error(`Failed to request the upload. Code: ${err.code}, message: ${err.message}`);
  });
} catch (err) {
  console.error(`Failed to request the upload. err: ${JSON.stringify(err)}`);
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
HarmonyOS
子站问答
访问
宣传栏