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为服务器返回的信息
})

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

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

参考示例:

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}`);
  }
}
分享
微博
QQ
微信
回复
2天前
相关问题
如何在Stage模型中创建后台服务
1962浏览 • 1回复 待解决
台服务器如何安装双centos系统?
2167浏览 • 1回复 待解决
HarmonyOS 沙箱访问获取不到文件
102浏览 • 1回复 待解决
HarmonyOS web桥原生代码方法
20浏览 • 1回复 待解决
服务下的前后台用户是否分开?
2780浏览 • 1回复 待解决
VScode终端ssh连接不到Linux服务器问题
28172浏览 • 2回复 待解决
HarmonyOS 文件上传服务器问题
393浏览 • 1回复 待解决
路由传参如何参?可否给个案例?
3200浏览 • 1回复 待解决
DevEco Studio真机调试找不到签名文件
698浏览 • 1回复 待解决