小程序上传图片到七牛云(支持多张上传,预览,删除)

以下为wxml (使用的vant小程序ui框架,需在json文件里自行引入)


    头像展示(必填)
      (选一张好看的个人照片可以增加客户点击的机会哦)
      
    
    
      
        {{item}}
        
      
      
    
  

以下为wxss

.clearFloat {
  clear: both;
  overflow: hidden;
}
.upload_title {
  color: #222;
  font-size: 32rpx;
  margin-bottom: 16rpx;
  display: block;
  margin-top: 50rpx;
}
.imgrelative {
  position: relative;
  height: 164rpx;
  width: 164rpx;
  margin-right: 43rpx;
  float: left;
}
.uploadimg {
  height: 164rpx;
  width: 164rpx;
  float: left;
}

以下为json

{
  "usingComponents": {
    "van-popup": "../../vant/popup/index",
    "van-area": "../../vant/area/index",
    "van-icon": "../../vant/icon/index",
    "van-toast": "../../vant/toast/index",
    "van-datetime-picker": "../../vant/datetime-picker/index",
    "van-field": "../../vant/field/index",
    "upload": "../../component/upload/index"
  }
}

以下为js文件(涉及到封装的微信ajax和七牛云上传图片方法在下面)

const util = require('../../utils/util.js');
const qiniuUploader = require("../../utils/qiniuUploader");
   
// 头像展示上传图片
  headIcon() {
    var that = this
    that.chooesImage(that, 1, function(res) {
      that.data.headIconArr.push(res)
      // console.log(that.data.ysCertImgArr.length)
      if (that.data.headIconArr.length >= 1) {
        that.setData({
          IsHeadIcon: false
        });
      }
      that.setData({
        headIconArr: that.data.headIconArr
      });
    })
  },
 // 头像展示预览与删除
  previewHeadIcon(e) {
    this._previewImage(e, this.data.headIconArr)
  },
  deleteHeadIcon(e) {
    var that = this
    that._deleteImage(e, that.data.headIconArr, function(files) {
      that.setData({
        headIconArr: files,
        IsHeadIcon: true
      });
    })
  },

 /*图片上传*/
  chooesImage(that, count, callback) {
    util.didPressChooesImage(that, count, function(filePath) {
      qiniuUploader.upload(filePath, (res) => {
          console.log(res)
          callback(res)
          that.checkSubmit()
        }, (error) => {
          console.error('error: ' + JSON.stringify(error));
        },
        null, // 可以使用上述参数,或者使用 null 作为参数占位符
        (progress) => {
          // console.log('上传进度', progress.progress)
          // console.log('已经上传的数据长度', progress.totalBytesSent)
          // console.log('预期需要上传的数据总长度', progress.totalBytesExpectedToSend)
        }, cancelTask => that.setData({
          cancelTask
        })
      );
    })
  },
/*图片预览*/
  _previewImage: function(e, arr) {
    var preUlrs = [];
    console.log(arr)
    const imgPath = 'https://cdn.wutongdaojia.com/'
    arr.map(
      function(value, index) {
        var key = imgPath + value.key
        preUlrs.push(key);
      }
    );
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: preUlrs // 需要预览的图片http链接列表
    })
  },
  /*图片删除*/
  _deleteImage: function(e, arr, callback) {
    var that = this;
    var files = arr;
    var index = e.currentTarget.dataset.index; //获取当前长按图片下标
    console.log(index)
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗?',
      success: function(res) {
        if (res.confirm) {
          files.splice(index, 1);
          console.log(files)
        } else if (res.cancel) {
          return false;
        }
        // files,
        that.setData({
          isCanAddFile: true
        });
        that.checkSubmit()
        callback(files)
      }
    })
  },

以下为封装的七牛云上传图片方法(util.js)

const qiniuUploader = require("./qiniuUploader");
import api from './api.js';

const getUploadToken = () => {
  var params = {
    token: wx.getStorageSync('token')
  }
  api.ajax("GET", params, "/weixin/getUploadToken").then(res => {
    console.log(res.data)
    initQiniu(res.data)
  });
}
// 初始化七牛相关参数
const initQiniu = (uptoken) => {
  var options = {
    region: 'NCN', // 华北区
    // uptokenURL: 'https://[yourserver.com]/api/uptoken',
    // cdn.wutongdaojia.com
    // uptokenURL: 'http://upload-z1.qiniup.com',
    // uptokenURL: 'https://yuesao.wutongdaojia.com/weixin/getUploadToken',
    // uptoken: 'xxx',
    uptoken: uptoken,
    // domain: 'http://[yourBucketId].bkt.clouddn.com',
    domain: 'space.bkt.clouddn.com',  // space为七牛云后台创建的空间
    shouldUseQiniuFileName: false
  };
  qiniuUploader.init(options);
}

export function didPressChooesImage(that, count, callback) {
  getUploadToken();
  // 微信 API 选文件
  wx.chooseImage({
    count: count,
    success: function(res) {
      console.log(res)
      var filePath = res.tempFilePaths[0];
      console.log(filePath)
      callback(filePath)
      // 交给七牛上传
    }
  })
}

/**
 * 文件上传
 * 服务器端上传:http(s)://up.qiniup.com
 * 客户端上传: http(s)://upload.qiniup.com
 * cdn.wutongdaojia.com
 */
function uploader(file, callback) {
  initQiniu();
  qiniuUploader.upload(filePath, (res) => {
      // 每个文件上传成功后,处理相关的事情
      // 其中 info 是文件上传成功后,服务端返回的json,形式如
      // {
      //    "hash": "Fh8xVqod2MQ1mocfI4S4KpRL6D98",
      //    "key": "gogopher.jpg"
      //  }
      // 参考http://developer.qiniu.com/docs/v6/api/overview/up/response/simple-response.html
      that.setData({
        'imageURL': res.imageURL,
      });
    }, (error) => {
      console.log('error: ' + error);
    },
    // , {
    //     region: 'NCN', // 华北区
    //     uptokenURL: 'https://[yourserver.com]/api/uptoken',
    //     domain: 'http://[yourBucketId].bkt.clouddn.com',
    //     shouldUseQiniuFileName: false
    //     key: 'testKeyNameLSAKDKASJDHKAS'
    //     uptokenURL: 'myServer.com/api/uptoken'
    // }
    null, // 可以使用上述参数,或者使用 null 作为参数占位符
    (res) => {
      console.log('上传进度', res.progress)
      console.log('已经上传的数据长度', res.totalBytesSent)
      console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend)
    });
};
module.exports = {
  initQiniu: initQiniu,
  getUploadToken: getUploadToken,
  didPressChooesImage: didPressChooesImage
}

封装小程序wx.request(api.js)

const ajax = (Type, params, url) => {
  var methonType = "application/json";
  // var https = "http://www.wutongdaojia.com"
  var https = "https://yuesao.wutongdaojia.com"
  var st = new Date().getTime()
  if (Type == "POST") {
    methonType = "application/x-www-form-urlencoded"
  }
  return new Promise(function (resolve, reject) {
    wx.request({
      url: https + url,
      method: Type,
      data: params,
      header: {
        'content-type': methonType,
        'Muses-Timestamp': st,
        'version': 'v1.0' // 版本号
        // 'Muses-Signature': sign
      },
      success: function (res) {
        // if (res.statusCode != 200) {
        //   reject({ error: '服务器忙,请稍后重试', code: 500 });
        //   return;
        // }
        // resolve(res.data);
        wx.hideLoading()
        console.log(res)
        if (res.data.status == 200) {
          resolve(res.data);
        } else if (res.data.status == 400) {
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 1000
          })
          return
        } else if (res.data.status == 401){
          wx.removeStorageSync('phone')
          wx.removeStorageSync('token')
          wx.showToast({
            title: res.data.message,
            icon: 'none',
            duration: 1000,
            success:function(){
              wx.navigateTo({
                url: '../login/index',
              })
            }
          })
          return
        } else {
          //错误信息处理
          wx.showToast({
            title: '服务器错误,请联系客服',
            icon: 'none',
            duration: 1000
          })
        }
      },
      fail: function (res) {
        // fail调用接口失败
        reject({ error: '网络错误', code: 0 });
      },
      complete: function (res) {
        // complete
      }
    })
  })
}

有什么不懂的可以加我微信(18310911617)
备注(说明来意)


你可能感兴趣的:(小程序,七牛云存储,上传图片)