用ajax上传图片到oss

本文介绍使用JavaScript和微信小程序实现阿里云OSS文件上传的方法,包括生成上传策略、签名和利用FormData进行文件上传的过程。
        var request = new FormData()
        request.append("OSSAccessKeyId",'xxxxxxxxxxxxxxxx');
        request.append("policy",policy);
        request.append("Signature",signature);
        var name = self.Oss.UUID()+this.files[0].name
        request.append("key",name);
        request.append("success_action_status",'200');
        request.append('file', this.files[0]);
        $.ajax({
          url:url,
          processData: false,
          cache: false,
          async: false,
          contentType: false,
         type: 'post',
          data:request,
          success:function(request){
            $(self.Oss.sendArray[i]).val(url+'/'+name) 
          }
        })

接口拿的数据:

   const host = `http://${config.bucket}.${config.region}.aliyuncs.com`
   const expireTime = new Date().getTime() + config.expAfter
   const expiration = new Date(expireTime).toISOString()
   const policyString = JSON.stringify({
      expiration,
      conditions: [
        ['content-length-range', 0, config.maxSize]
      ]
    })
   const policy = Buffer.from(policyString).toString('base64')
   const signature = crypto.createHmac('sha1', 
   config.accessKeySecret).update(policy).digest("base64")

config.accessKeySecret、config.region、config.bucket:阿里云拿的

 

 

-----------------------------------------------------下面是小程序的-------------------------

1.通过chooseImage选择照片,返回的是一个地址数组。

2.然后通过uploadFile上传到阿里云


import ajax from '@U/ajax'
var ossParam = {
  count: 6,
  url: "/oss/sign",
  index: 0,
  imgTempUrl: [],
  _cbImgs:[]
}
export default{
  newGuid(){
    let guid = ''
    for (let i = 1; i <= 32; i++) {
      let n = Math.floor(Math.random()*16.0).toString(16)
      guid += n
      if ((i==8) || (i==12) || (i==16) || (i==20)) {
        guid += "-"
      }
    }
    return guid
  },
  // 选择图片
  chooseImg(sourceType, chooseCb){
    var self = this
    wx.chooseImage({
      count: 6,
      sourceType: sourceType,
      success: (res)=>{
        wx.showLoading({
          title: "加载中",
          mask: true
        })
        ossParam.imgTempUrl = res.tempFiles
        ossParam.count = res.tempFiles.length
        self._upload(chooseCb)     
      }
    })
  },
  _upload(cb){
    if(ossParam.index < ossParam.count){
      //继续上传
      let filePath = ossParam.imgTempUrl[ossParam.index].path
      this.uploadImage(filePath,cb)      
    }else{
      //返回结果
      cb && cb(ossParam._cbImgs)
      return
    }
  },
  uploadImage(filePath,cb){
    let self = this;
    ajax.get(ossParam.url, {
      success:function(ossRes) {
        var key = self.newGuid();
         wx.uploadFile({
          url: ossRes.data.host,
          filePath: filePath,
          name: 'file',
          formData: {
            name: "123",
            key: key,
            policy: ossRes.data.policy,
            OSSAccessKeyId: ossRes.data.OSSAccessKeyId,
            success_action_status: '200',
            signature: ossRes.data.signature
          },
          success: result => {
            if (result.statusCode === 200) {
              let _tempUrl = `${ossRes.data.host}/${key}`
              ossParam._cbImgs.push(_tempUrl);
              ossParam.index ++ ;
              self._upload(cb)
            } 
          },
          fail: err => {
            failCb && failCb()                               
          }
        })
      },
      fail:()=>{
        wx.hideLoading();
        console.log("err: "+ err)
      }
    })
  }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值