OpenHarmony 提交上传文件(request)

程皖Orz
发布于 2023-9-23 18:29
浏览
0收藏

首先得到应用的缓冲路径

import common from '@ohos.app.ability.common';
let context = getContext(this) as common.UIAbilityContext;
let cacheDir = context.cacheDir;

然后得到想要修改文件的file路径

let file = fs.openSync(globalThis.url_file, fs.OpenMode.CREATE);
      fs.copyFile(file.fd, cacheDir + '/testt.jpg', (err) => {
        if (err) {
          AlertDialog.show({
            message: JSON.stringify(err )+'\r\n',
          })
          console.info("copy file failed with error message: " + err.message + ", error code: " + err.code);
        } else {
          AlertDialog.show({
            message: JSON.stringify("成功复制文件" +cacheDir)+'\r\n',
          })
          console.info("copy file success");
        }
      });

下一步是提交上传

// 上传任务配置项
let uploadConfig = {
  url: 'http://192.168.3.8:2233/',
  header: { key1: 'Content-Type', key2: 'multipart/form-data',Filename:"22.jpg" },
  //header: { key1: 'Content-Type', key2: 'multipart/form-data',Filename:"22.jpg" },
  method: 'POST',
  files: [
    { filename: 'test.jpg', name: 'test', uri: "internal://cache/" + 'testt.jpg', type: 'jpg' }
  ],
  data: [
    { name: 'Filename', value: 'FP000008' }
  ]
}



  try {
    request.uploadFile(context, uploadConfig)
      .then((uploadTask) => {
        uploadTask.on('complete', (taskStates) => {
          for (let i = 0; i < taskStates.length; i++) {
          }
        });
      })
      .catch((err) => {
        console.error(`xx Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);
      })
  } catch (err) {
    console.error(`xx Invoke uploadFile failed, code is ${err.code}, message is ${err.message}`);

  }

收藏
回复
举报
回复
    相关推荐