鸿蒙开发app上传图片到阿里云oss

244 阅读1分钟
首先吐糟下阿里云官方,还没出鸿蒙版本oss的sdk,正常应该很多app都是接阿里云oss上传的啊,而且我感觉封装一个oss的sdk也不难,核心的就是图片上传

问题:阿里云官方不提供,但是我们项目没法等啊,问题还得要解决,也只能自己解决 可行的解决方案:

  1. app中嵌入web,把图片地址传给web,由web调用web的oss sdk,web去上传到oss上(应该是可行的,但是经过web是不稳定的,并且界面怎么办,不可能所有上传界面都用web来做)
  2. app传图片到自己服务器,自己服务器再上传到阿里云oss(可行,但是这种往往需要压缩图片,否则会很久或者链接会断开,因为这里经过了两次上次图片文件,你传服务器,服务器传给阿里云)
  3. app尝试客户端直传方式给阿里云oss(弄了挺长时间,不断修改,最终测试可行)。参考文档: help.aliyun.com/zh/oss/use-…

核心代码:

let formData: Array<http.MultiFormData> = []
  try {
     formData = [
      { name: 'name', contentType: 'text/plain', data: file.name },
      { name: 'policy', contentType: 'text/plain', data: data.policy },
      { name: 'OSSAccessKeyId', contentType: 'text/plain', data: accesskeyId },
      { name: 'success_action_status', contentType: 'text/plain', data: '200' },
      { name: 'signature', contentType: 'text/plain', data: data.signature },
      { name: 'key', contentType: 'text/plain', data: `${dir}${name}` },
      { name: 'file', contentType: 'text/plain', filePath: file.path, remoteFileName: file.name }
    ]
  } catch (e) {
    uploadCallback()
  }

我自己写了一个成功上传到oss的demo。如果你要参考我写的代码,可评论或者私信我。