HarmonyOS request.uploadFile 上传多文件?

在使用request.uploadFile实现 multipart/form-data 一个请求上传多个文件,抓包发现,会发起多次请求,每次上传一个文件。

async uploadFile(context: common.UIAbilityContext, func: string, params?: object, method?: http.RequestMethod, expectDataType?: http.HttpDataType): Promise<string> {

  let netUrl = `${NetHelper.getBaseUrl(this.netWork, params)}${func}`;

  let fileName: string = "";
  let fileList = params["fileList"] as string [];
  let files: request.File [] = [];

  for(let filePath of fileList) { // 文件集合
  fileName = filePath.substring(filePath.lastIndexOf("/")+1, filePath.length);
  let parentDir: string | null = FileManager.getParentDir(filePath);
  if (parentDir != FilePathGenerator.cacheDir) {
  FileManager.copyFileSync(filePath, `${FilePathGenerator.cacheDir}/${fileName}`);
}
let suffixIndex = fileName.lastIndexOf(".");
files.push({ filename: fileName, name: fileName, uri:  "internal://cache/" + fileName,
  type: suffixIndex >= 0 ? fileName.substring(suffixIndex + 1, fileName.length) : "" });
}

let uploadConfig: request.UploadConfig = {
  url: netUrl,
  header: headers,
  method: method?.valueOf(),
  files: files,
  data: datas,
};

return new Promise(async (resolve, reject) => {
  try {
    const uploadTask = await request.uploadFile(context, uploadConfig);
    uploadTask.on('complete', (taskStates: Array<request.TaskState>) => {
      logger.debug('taskStates');
      logger.debug('taskStates[0].message:' + taskStates[0].message);
      return resolve(taskStates[0].message);
    });
    uploadTask.on("progress",(receivedSize: number, totalSize: number)=> {
      logger.debug("progress",  `receivedSize: ${receivedSize} totalSize:${totalSize}`);
    });
  } catch (e) {
    logger.error("uploadFile error:", e);
    reject(new RYError("", RYErrorCode.UploadError, e));
  }
})
}
阅读 521
logo
HarmonyOS
子站问答
访问
宣传栏