HarmonyOS 文件上传接口数据返回信息?

在使用request.uploadFile(context, uploadConfig) 文件上传是只能监听到uploadTask.off(‘complete’, upCompleteCallback1);文件是否上传成功的信息,无法获取服务端处理文件按后返回的字段信息。

请问如果需要获取到服务端处理文件后返回的数据应该怎么操作?

阅读 488
1 个回答

可以尝试订阅服务端请求信息,获取的headers中包含有header和body,参考文档:

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-websocket-V5\#onheaderreceive12

demo如下:

import { BusinessError, request } from '@kit.BasicServicesKit';
@Entry
@Component
struct UploadFile {
  @State message: string = 'Hello World';
  upload() {
    let uploadConfig: request.UploadConfig = {
      url: 'http://huawei.com', // 需要手动将 url 替换为真实服务器的 HTTP 协议地址
      header: { 'Accept': '/' },
      method: "POST",
      files: [{
        filename: "test",
        name: "test",
        uri: "internal://cache/test.jpg",
        type: "jpg"
      }],
      data: [{ name: "name123", value: "123" }],
    };
    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)});
    }
  }
  build() {
    Column() {
      Button('上传').onClick(() => {
        this.upload()
      })
    }.width('100%').height('100%').justifyContent(FlexAlign.Center)
  }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
logo
HarmonyOS
子站问答
访问
宣传栏