小程序用阿里云OSS上传图片

2019-08-19  本文已影响0人  姬歌

用法

const aliyunManager = require('../../../../utils/aliyunOSS/aliyunManager.js')
Page({
    uploadImage: function(localUrl) {
    aliyunManager.uploadFile({
      filePath: localUrl,
      success: function(path) {
        console.log(path)    //返回网络图片地址
      },
      fail: function(err) {
      }
    })
  }
})

工具类源码

说明:此工具中的签名参数都是后台动态返回,并非本地固定配置。所以不需要base64,crypto等工具包。

//aliyunManager.js

const httpManager = require('../HttpManager.js')

var manager = {

  signRefreshDate: undefined, //最后一次获取签名时间
//需从服务器获取的签名配置参数
  accessKeyId: undefined,
  bucket: undefined,
  policy: undefined,
  signature: undefined,
  timeout: undefined, //签名超时时间,单位:分钟

  getSignInfo: function({ filePath, success, fail }) {

    let that = this
    var needRequestInfo = true
/****************************可忽略此段,判断是否过期(sign info 可以重复使用)****************************/
     if (that.signRefreshDate != undefined) {
      if (that.timeout == undefined) {
        that.timeout = 10 //默认180分钟,但异常状态只给10分钟
      }
      let currentTime = new Date()
      let miliSeconds = currentTime.getTime() - that.signRefreshDate.getTime()
      if (miliSeconds * 1000 < timeout * 60) {
        //还没失效
        console.log('还没失效!!可直接使用')
        needRequestInfo = false
        that.uploadFileAfterGetSign({  filePath, success, fail })
      } else {
        //失效了!!
        console.log('失效了!!')
      }
    }
    /****************************可忽略此段  end****************************/

   /****************************从服务器获取签名配置参数****************************/
    if (needRequestInfo) {
      console.log('(重新)请求签名参数!')
      httpManager.postRq({
        api: 'ossStsToken',
        success: function(e) {
          console.log(e)
          let data = e.data.data
          that.accessKeyId = data.accessKeyId
          that.bucket = data.bucket
          that.policy = data.policy
          that.signature = data.signature
          that.timeout = data.timeout

          that.uploadFileAfterGetSign({ filePath, success, fail })
        },
        fail: function(e) {
          fail(e)
        }
      })
    }
  },
//上传图片到阿里云
  uploadFileAfterGetSign: function({ filePath, success, fail }) {

    let aliyunServerURL = "https://" + this.bucket + "/"
    let dirInOSSDomain = 'programNameAsDirectory'
    let fileKey = dirInOSSDomain + '/' + new Date().getTime() + '_' + Math.floor((Math.random() * 1000) + 1) + '.png';
    let that = this

    let fData = {
      'key': fileKey,        //图片在阿里云上的子路径,可包含(创建)子目录。
      'OSSAccessKeyId': that.accessKeyId,
      'policy': that.policy,
      'Signature': that.signature,
      'success_action_status': '200',
    }
    console.log(fData)

    wx.uploadFile({
      url: aliyunServerURL, //仅为示例,非真实的接口地址
      filePath: filePath,
      name: 'file',
      formData: fData,
      success: function(res) {
        if (res.statusCode != 200) {
          fail({errCode: '599', msg:'其他错误'})
          return;
        }
        let imagePath = aliyunServerURL + fileKey
        success(imagePath)
        console.log('上传图片成功', res)
      },
      fail: function(err) {
        fail(err)
      },
    })
  },

  uploadFile: function({ filePath, success, fail }) {
    if (!filePath || filePath.length < 9) {
      wx.showModal({
        title: '文件路径错误',
        content: '请重试',
        showCancel: false,
      })
      return;
    }
    this.getSignInfo({
      filePath, success, fail
    })
  }
}


module.exports = {
  //内部用;不导出,内部也用不了会报错。xxx is not a fuction..
  uploadFileAfterGetSign: manager.uploadFileAfterGetSign,
  getSignInfo: manager.getSignInfo,
  //外部用
  uploadFile: manager.uploadFile
};

如果出现错误'You have no right to access this object because of bucket acl.',请在阿里云控制台检查配置。

白名单报错问题:
'xxx.aliyuncs.com 不在以下 uploadFile 合法域名列表中'
需要在【uploadFile合法域名】中添加相关的域名'xxx.aliyuncs.com'
添加后,差不多一个小时才正常。。。其他域名几乎就是立即生效,也许企鹅想是故意恶心一下竞争对手的产品的缘故。
如果要下载,在【downloadFile合法域】名中也要配置一下。一次性配置好,毕竟每个月只有5次机会修改域名。

上一篇 下一篇

猜你喜欢

热点阅读