微信小程序上传图片到七牛融合 CDN

1.引入包

下载地址: http://7xvilo.com1.z0.glb.clouddn.com/qiniu-wxapp-sdk-master.zip

2.初始化七牛

const qiniuUploader  = require("../../state/qiniuUploader.js");
// 初始化七牛相关参数
function initQiniu(that) {
  var options = {
    uploadURL:"https://up-z1.qbox.me",//根据区域找地址
    region: 'NCN', // 华北区
    uptoken: that.data.qiniuToken,//token由后端接口获取后的token值,其他方法参考文档
    domain: 'http://phq1b7zvy.bkt.clouddn.com/',
    shouldUseQiniuFileName: false
  };
  qiniuUploader.init(options);
}

3.上传操作

chooseImage:function(e){
    var that=this;
    //初始化七牛
    initQiniu(that);
    console.log()
    // 微信 API 选文件
    wx.chooseImage({
      count: 1,
      success: function (res) {
        var filePath = res.tempFilePaths[0];
        // 交给七牛上传
        qiniuUploader.upload(filePath, (res) => {
          that.setData({
            imageObject:res,
            'userheadimg': res.imageURL,
          })
        }, (error) => {
          console.error('error: ' + JSON.stringify(error));
        },null, (progress) => {
          console.log('上传进度', progress.progress)
          console.log('已经上传的数据长度', progress.totalBytesSent)
          console.log('预期需要上传的数据总长度', progress.totalBytesExpectedToSend)
        }, cancelTask => that.setData({ cancelTask })
        );
      }
    })
  }

相关文档:

https://github.com/gpake/qiniu-wxapp-sdk/blob/master/README.md

你可能感兴趣的:(微信小程序)