HarmonyNext上传用户相册图片到服务器

图片选择就不用说了,直接用

无须申请权限 。

上传图片,步骤和android对比稍微有点复杂,可能是为了安全性考虑,需要将图片先拷贝到缓存目录下面,然后再上传,当然你也可以转成Base64,然后和服务端沟通。

这里是拷贝到缓存目录中

拷贝函数是:

public static async copyFileToCache(cacheDir: string, uri: string): Promise<string> {
  let id = uri.split('/').pop()?.split('.')[0];
  let imagePath = `${cacheDir}/${id}.jpg`;
  let file = await fileIo.open(uri, fs.OpenMode.READ_ONLY);
  try {
    fileIo.copyFileSync(file.fd, imagePath);
  } catch (err) {
    logger.info(`copyFileToCache copyFileSync err = ${err}`);
  }
  await fileIo.close(file.fd);
  return imagePath;
}

如果是列表,你也可以循环操作

上传是用的axios:

axios.post<HdResponse<UserPhotoBean>, AxiosResponse<HdResponse<UserPhotoBean>>, FormData>(BasicConstant.REQUES_URL +
AppApi.UPLOAD_PHOTO, formData, {
  headers: {
    'Content-Type': 'multipart/form-data'
  },
  context: context,
  onUploadProgress: (progressEvent: AxiosProgressEvent): void => {
    console.info(progressEvent && progressEvent.loaded && progressEvent.total ?
      Math.ceil(progressEvent.loaded / progressEvent.total * 100) + '%' : '0%');
  },
}
).then((res: AxiosResponse<HdResponse<UserPhotoBean>>) => {
  console.info("result" + JSON.stringify(res.data));
  resolve(res.data)
}).catch((err: AxiosError) => {
  reject()
  console.error("error:" + JSON.stringify(err));
})

至此,所有操作就完成了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

carden_coder

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值