HarmonyOS 后台服务接不到文件?

uploadPics(){
  let fileUris = this.copyFileToSandBox();

  let files: Array<request.File> = []
  for (let i = 0; i < fileUris.length; i++) {
    let file = fs.openSync(fileUris[i],fs.OpenMode.READ_ONLY);
    let stat = fs.lstatSync(fileUris[i]);
    fs.closeSync(file.fd);
    let filename = fileUris[i].substring(fileUris[i].lastIndexOf("/") + 1);
    let name = filename.substring(0,filename.indexOf("."));
    let fileType = filename.substring(filename.indexOf(".") + 1);
    let path = fileUris[i].substring(fileUris[i].lastIndexOf("/cache"))
    files.push({
      filename: name,
      name: "files",
      uri: "internal:/" + path,
      type: fileType
    })
  };
  let header = new Map<Object, string>();
  header.set("Content-type","multipart/form-data")
  let data : Array<request.RequestData> = [{name:"serviceCode",value:"handheld_bus_file"},{name:"twoServiceCode",value:"feedback"}];
  let uploadConfig: request.UploadConfig = {
    url: UrlConst.ROOT_URL + UrlConst.FILE_UPLOAD_URL,
    header: header,
    method: 'POST',
    files: files,
    data: data
  }
  try {
    request.uploadFile(getContext(this), 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])}`);
          }
        });
        uploadTask.on("headerReceive",(header:object)=>{
          console.log(JSON.stringify(header));
          //header.body为服务器返回的信息
        })
        /*uploadTask.delete(()=>{})
        uploadTask.off('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}`);
  }

}

使用上述代码上传文件时,在

uploadTask.on("headerReceive",(header:object)=>{
  console.log(JSON.stringify(header));
  //header.body为服务器返回的信息
})

中接到文件不能为空,跟进后台后发现,无文件上传到服务器,该接口在友商平台调用正常,缓存中的文件有数据,未能分析出代码问题

阅读 497
1 个回答

参考示例:

uploadPics(){
  let fileUris = this.copyFileToSandBox();
  this.caches = fileUris;
  let files: Array<request.File> = []
  for (let i = 0; i < fileUris.length; i++) {
    let file = fs.openSync(fileUris[i],fs.OpenMode.READ_ONLY);
    let stat = fs.lstatSync(fileUris[i]);
    fs.closeSync(file.fd);
    let filename = fileUris[i].substring(fileUris[i].lastIndexOf("/") + 1);
    let name = filename.substring(0,filename.indexOf("."));
    let fileType = filename.substring(filename.indexOf(".") + 1);
    let path = fileUris[i].substring(fileUris[i].lastIndexOf("/cache"))
    files.push({
      filename: name,
      name: "files",
      uri: "internal:/" + path,
      type: fileType
    })
  };
  let formHeader = new Map<Object, string>();
  formHeader.set("Content-type","multipart/form-data")
  let formData : Array<request.RequestData> = [{name:"serviceCode",value:"handheld_bus_file"},
    {name:"twoServiceCode",value:"feedback"},
    {name:"lasting",value:"false"}
  ];
  let uploadConfig: request.UploadConfig = {
    url: UrlConst.ROOT_URL + UrlConst.FILE_UPLOAD_URL,
    header: formHeader,
    method: 'POST',
    files: files,
    data: formData
  }
  try {
    request.uploadFile(getContext(this), uploadConfig)
      .then((uploadTask: request.UploadTask) => {
        uploadTask.on('complete', (taskStates: Array<request.TaskState>) => {
          //删除缓存的文件
          this.deleteCache();
          this.submitMsg();

        });
        uploadTask.on("headerReceive",(header:ESObject)=> {
          if (header && header.body ){
            let data : ESObject = header.body
            let rst : BaseModel<FileUpInfo[]> = JSON.parse(header.body) as BaseModel<FileUpInfo[]>;
            let files : FileUpInfo[] | undefined = rst.result
            if (files && files.length > 0) {
              let temp : string[] = [];
              files.forEach((item:FileUpInfo) => {
                let url = "/sys/common/file-preview?id=" + item.id + "&preview=true";
                temp.push(url);
              })
              this.pics = temp;
            }
          }

        })
      })
      .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}`);
  }
}
logo
HarmonyOS
子站问答
访问
宣传栏