封装Oss上传

import Http from './http'
export default {
  decode(e) {
    this._keyStr =
      'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
    var t = ''
    var n, r, i
    var s, o, u, a
    var f = 0
    e = e.replace(/[^A-Za-z0-9+/=]/g, '')
    while (f < e.length) {
      s = this._keyStr.indexOf(e.charAt(f++))
      o = this._keyStr.indexOf(e.charAt(f++))
      u = this._keyStr.indexOf(e.charAt(f++))
      a = this._keyStr.indexOf(e.charAt(f++))
      n = (s << 2) | (o >> 4)
      r = ((o & 15) << 4) | (u >> 2)
      i = ((u & 3) << 6) | a
      t = t + String.fromCharCode(n)
      if (u != 64) {
        t = t + String.fromCharCode(r)
      }
      if (a != 64) {
        t = t + String.fromCharCode(i)
      }
    }
    t = this._utf8_decode(t)
    return t
  },
  _utf8_decode(e) {
    e = e.replace(/rn/g, 'n')
    var t = ''
    for (var n = 0; n < e.length; n++) {
      var r = e.charCodeAt(n)
      if (r < 128) {
        t += String.fromCharCode(r)
      } else if (r > 127 && r < 2048) {
        t += String.fromCharCode((r >> 6) | 192)
        t += String.fromCharCode((r & 63) | 128)
      } else {
        t += String.fromCharCode((r >> 12) | 224)
        t += String.fromCharCode(((r >> 6) & 63) | 128)
        t += String.fromCharCode((r & 63) | 128)
      }
    }
    return t
  },
  UploadImage(file) {
    if (!file) {
      return
    }
    let reader = new FileReader()
    let imgBase64
    let url
    reader.readAsArrayBuffer(file)
    reader.onloadend = function(e) {
      imgBase64 = e.target.result
    }
    let kind = file.type.split('/')[1]
    let ossurl = ''
    let BaseUrl
    if (process.env.NODE_ENV === 'development') {
      BaseUrl = 'https://xxx-test.xxx.com'
    } else {
      BaseUrl = 'https://api.xxx.com'
    }
    let urlto =
      BaseUrl + `/api/tank/xxx/?origin_name=${file.name}&kind=${kind}`
    return new Promise((resolve, reject) => {
      Http.get(urlto)
        .then((res) => {
          ossurl = this.decode(res.body.oss_url)
          const xhr = new XMLHttpRequest()
          xhr.open('PUT', ossurl)
          xhr.send(imgBase64)
          xhr.onload = function() {
            url = xhr.responseURL.split('?')[0]
            resolve(url)
          }
        })
        .catch((err) => {
          reject(err)
        })
    })
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值