HarmonyOS 不在cache目录下的文件怎么上传?

从相册选择的图片需要做上传,但是使用系统提供的上传方法,发现只有cache目录下的文件才能上传成功,请问非cache目录下的文件如果上传?

参考文档:

https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/app-file-upload-download-V5

代码如下:

地址:file://media/Photo/3/IMG_1710398715_002/IMG_2024314_144335.jpg

错误码:Invoke uploadFile failed, code is 401, message is the parameters check fails this is fail path

// 上传任务配置项
let header = new Map<Object, string>();
header.set('appKey', this.tokenBean?.cystorageAppKey ?? '');
header.set('token', this.tokenBean?.securityToken ?? '');
header.set('contextId', this.tokenBean?.contextId ?? '');
header.set('expires', expires);

let files: Array<request.File> = [
  { filename: fileName, name: 'file', uri: 'file://media/Photo/1/IMG_1706403774_000/screenshot_20240128_090114.jpg', type: 'jpg' }
]
let data: Array<request.RequestData> = [{ name: 'name', value: 'value' }];
let uploadConfig: request.UploadConfig = {
  url: uploadUrl,
  header: header,
  method: 'POST',
  files: files,
  data: data
}

// 将本地应用文件上传至网络服务器
try {
  request.uploadFile(this.inputBean?.context!, 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])}`);
        }
      });
    })
    .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}`);
}
HarmonyOS
1天前
浏览
收藏 0
回答 1
待解决
回答 1
按赞同
/
按时间
put_get

将公共路径的文件(picker选择),拷贝至沙箱路径中,可完成上传。

Demo:

pickerPhoto() {
  try {
    let options = new picker.PhotoSelectOptions();
    options.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
    options.maxSelectNumber = 1;
    let p = new picker.PhotoViewPicker();

    p.select(options).then((res:picker.PhotoSelectResult) => {
      console.info("tag photo is uri" + res.photoUris[0])
      this.saveFile(res.photoUris[0]);
    })
  } catch (e) {
    console.error("tag select tailed..")
  }
}


async saveFile(uri: string) {
  // 将公共目录的文件,拷贝至沙箱路径
  let destDist = getContext(this).cacheDir + "/test.png";

  let src = fs.openSync(uri, fs.OpenMode.READ_ONLY);
  let dst = fs.openSync(destDist, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
  fs.copyFileSync(src.fd, dst.fd);
}

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

https://developer.huawei.com/consumer/cn/doc/harmonyos-references-V5/js-apis-request-V5#onheaderreceive7

分享
微博
QQ
微信
回复
1天前
相关问题
java怎么读取公共目录下文件
2307浏览 • 1回复 待解决
鸿蒙如何读取resources目录下文件
3554浏览 • 1回复 待解决
如何获取工程目录下json文件
887浏览 • 1回复 待解决
canvas怎么绘制资源目录下图片
702浏览 • 1回复 待解决
资源目录下文件到沙箱单向流动
1041浏览 • 1回复 待解决
HarmonyOS文件上传怎么
592浏览 • 1回复 待解决