• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

微信小程序 上传图片到七牛云 支持多张

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

封装七牛云上传方法 qiniuUploader.js

(function () {

  var config = {
    qiniuRegion: '',
    qiniuImageURLPrefix: '',
    qiniuUploadToken: '',
    qiniuUploadTokenURL: '',
    qiniuUploadTokenFunction: null,
    qiniuShouldUseQiniuFileName: false
  }

  module.exports = {
    init: init,
    upload: upload,
  }

  // 在整个程序生命周期中,只需要 init 一次即可
  // 如果需要变更参数,再调用 init 即可
  function init(options) {
    config = {
      qiniuRegion: '',
      qiniuImageURLPrefix: '',
      qiniuUploadToken: '',
      qiniuUploadTokenURL: '',
      qiniuUploadTokenFunction: null,
      qiniuShouldUseQiniuFileName: false
    };
    updateConfigWithOptions(options);
  }

  function updateConfigWithOptions(options) {
    

    if (options.region) {
      config.qiniuRegion = options.region;
    } else {
      console.error('qiniu uploader need your bucket region');
    }
    if (options.uptoken) {
      config.qiniuUploadToken = options.uptoken;
    } else if (options.uptokenURL) {
      config.qiniuUploadTokenURL = options.uptokenURL;
    } else if (options.uptokenFunc) {
      config.qiniuUploadTokenFunction = options.uptokenFunc;
    }
    if (options.domain) {
      config.qiniuImageURLPrefix = options.domain;
    }
    config.qiniuShouldUseQiniuFileName = options.shouldUseQiniuFileName
  }

  function upload(filePath, success, fail, options, progress, cancelTask) {
    

    if (null == filePath) {
      console.error('qiniu uploader need filePath to upload');
      return;
    }
    if (options) {
      
      updateConfigWithOptions(options);
    }
    if (config.qiniuUploadToken) {
     
      doUpload(filePath, success, fail, options, progress, cancelTask);
    } else if (config.qiniuUploadTokenURL) {
     
      getQiniuToken(function () {
        doUpload(filePath, success, fail, options, progress, cancelTask);
      });
    } else if (config.qiniuUploadTokenFunction) {
      
      config.qiniuUploadToken = config.qiniuUploadTokenFunction();
      if (null == config.qiniuUploadToken && config.qiniuUploadToken.length > 0) {
        console.error('qiniu UploadTokenFunction result is null, please check the return value');
        return
      }
       
      doUpload(filePath, success, fail, options, progress, cancelTask);
    } else {
      console.error('qiniu uploader need one of [uptoken, uptokenURL, uptokenFunc]');
      return;
    }
  }

  function doUpload(filePath, success, fail, options, progress, cancelTask) {
    if (null == config.qiniuUploadToken && config.qiniuUploadToken.length > 0) {
      console.error('qiniu UploadToken is null, please check the init config or networking');
      return
    }

    var url = uploadURLFromRegionCode(config.qiniuRegion);
    
    var fileName = filePath.split('//')[1];
    if (options && options.key) {
      fileName = options.key;
    }
    var formData = {
      'token': config.qiniuUploadToken
    };
    if (!config.qiniuShouldUseQiniuFileName) {
      formData['key'] = fileName
    }

   
    var uploadTask = wx.uploadFile({
      url: url,
      filePath: filePath,
      name: 'file',
      formData: formData,
      success: function (res) {
        var dataString = res.data
        if (res.data.hasOwnProperty('type') && res.data.type === 'Buffer') {
          dataString = String.fromCharCode.apply(null, res.data.data)
        }
        try {
          var dataObject = JSON.parse(dataString);
          //do something
          var imageUrl = config.qiniuImageURLPrefix + '/' + dataObject.key;
          dataObject.imageURL = imageUrl;
          console.log(dataObject);
          if (success) {
            success(dataObject);
          }
        } catch (e) {
          console.log('parse JSON failed, origin String is: ' + dataString)
          if (fail) {
            fail(e);
          }
        }
      },
      fail: function (error) {
        console.error(error);
        if (fail) {
          fail(error);
        }
      }
    })

    uploadTask.onProgressUpdate((res) => {
      progress && progress(res)
    })

    cancelTask && cancelTask(() => {
      uploadTask.abort()
    })
  }

  function getQiniuToken(callback) {
    wx.request({
      url: config.qiniuUploadTokenURL,
      success: function (res) {
        var token = res.data.uptoken;
        if (token && token.length > 0) {
          config.qiniuUploadToken = token;
          if (callback) {
            callback();
          }
        } else {
          console.error('qiniuUploader cannot get your token, please check the uptokenURL or server')
        }
      },
      fail: function (error) {
        console.error('qiniu UploadToken is null, please check the init config or networking: ' + error);
      }
    })
  }

  function uploadURLFromRegionCode(code) {
    var uploadURL = null;
    switch (code) {
      case 'ECN': uploadURL = 'https://up.qbox.me'; break;
      case 'NCN': uploadURL = 'https://up-z1.qbox.me'; break;
      case 'SCN': uploadURL = 'https://up-z2.qbox.me'; break;
      case 'NA': uploadURL = 'https://up-na0.qbox.me'; break;
      case 'ASG': uploadURL = 'https://up-as0.qbox.me'; break;
      default: console.error('please make the region is with one of [ECN, SCN, NCN, NA, ASG]');
    }
    return uploadURL;
  }

})();

封装的上传方法 publishashx.js

var utiltime = require('../../../../utils/time.js')
var utilsign = require('../../../../utils/getsign.js')
const app = getApp()
// 图片上传
// function addcompressionimg(images) {
//   var _sign = '';
//   var _time = utiltime.getTimems();

//   var arr = new Array();

//   for (var i = 0; i < images.length; i++) {
//     var dic = new Array();
//     dic["images"] = images[i];
//     dic["compression"] = images[i];
    
//     arr[i] = dic;

//   }

//   _sign = utilsign.getSign(_time, arr)


//   // console.log('{"data":' + datajson + ',"sign":"' + _sign + '","source":"weipro","timeStamp":' + _time + '}')
//   wx.request({
//     url: app.globalData.APIUrl +'/svc/api/Comment/compression', //仅为示例,并非真实的接口地址     
//     data: {
//       paramJson: '{"data":' + datajson + ',"sign":"' + _sign + '","source":"weipro","timeStamp":' + _time + '}'
//     },
//     header: {
//       'content-type': 'application/x-www-form-urlencoded' // 默认值
//     },
//     method: 'POST',
//     success: function (res) {
//       // console.log('上传图片')
//       // console.log(res)
//     },
//     fail: function (res) {
//     }
//   })
// }
function uptokencallback(path,callback){
  var datajson = '"{';
  var body = '';

  body += 'key' + path
  datajson += '\'key\':\'' + path + '\',';

  datajson = datajson.substring(0, datajson.length - 1);
  datajson += '}"';
  var _time = utiltime.getTimems();
  var _sign = ''; 
  _sign = utilsign.getSign(_time, body)
 
  wx.request({
    url: app.globalData.APIUrl + '/svc/api/qiniu/uptoken', //仅为示例,并非真实的接口地址     
    data: {
      paramJson: '{"data":' + datajson + ',"sign":"' + _sign + '","source":"weipro","timeStamp":' + _time + '}'
    },
    header: {
      'content-type': 'application/x-www-form-urlencoded' // 默认值
    },
    method: 'POST',
    success: function (res) {
      if (res.data.status =='success'){
        callback(res)
      }
    },
    fail: function (res) {
    }
  })
}
// function compression(imagesUrls){
//   var datajson = '"{';
//   var body = '';
 
//   if (imagesUrls != '') {
//     imagesUrls.sort()
//     var tmpimgs = '';
//     for (let i = 0; i < imagesUrls.length; i++) {
//       tmpimgs += "|" + imagesUrls[i]
//     }
//     body += 'imagesList' + tmpimgs
//     datajson += '\'imagesList\':\'' + tmpimgs + '\',';
//   } 
//   datajson = datajson.substring(0, datajson.length - 1);
//   datajson += '}"';
//   var _sign = '';
//   var _time = utiltime.getTimems();
//   _sign = utilsign.getSign(_time, body)

//   // console.log('{"data":' + datajson + ',"sign":"' + _sign + '","source":"weipro","timeStamp":' + _time + '}')
//   wx.request({
//     url: app.globalData.APIUrl + '/svc/api/Comment/compression', //仅为示例,并非真实的接口地址     
//     data: {
//       paramJson: '{"data":' + datajson + ',"sign":"' + _sign + '","source":"weipro","timeStamp":' + _time + '}'
//     },
//     header: {
//       'content-type': 'application/x-www-form-urlencoded' // 默认值
//     },
//     method: 'POST',
//     success: function (res) {
//       // console.log(res);
//     },
//     fail: function (res) {
//     }
//   })

// }
//添加评论
// function addComment(goodsId, userId, text, orderid, imagesUrls) {
  
//   var datajson = '"{';
//   var body = '';

//   var arr = new Array();
 
//   if (goodsId != '') {
//     body += 'goodsId' + goodsId 
//     datajson += '\'goodsId\':\'' + goodsId + '\',';
//   }
//   if (imagesUrls != '') {
//     imagesUrls.sort()
//     addcompressionimg(imagesUrls)
//     var tmpimgs = '';
//     for (let i = 0; i < imagesUrls.length;i++){
//       tmpimgs += "|" + imagesUrls[i]
//     }
//     body += 'imagesUrls' + tmpimgs
//     datajson += '\'imagesUrls\':\'' + tmpimgs + '\',';
//   }
//   if (orderid != '') {
//     body += 'orderId' + orderid 
//     datajson += '\'orderId\':\'' + orderid + '\',';
//   }
//   if (text != '') {
//     body += 'text' + text 
//     datajson += '\'text\':\'' + text + '\',';
//   }
//   if (userId != '') {
//     body += 'userId' + userId 
//     datajson += '\'userId\':\'' + userId + '\',';
//   } 
 
//   datajson = datajson.substring(0, datajson.length - 1);
//   datajson += '}"';
//   var _sign = '';
//   var _time = utiltime.getTimems(); 
//   _sign = utilsign.getSign(_time, body)

//   // console.log('{"data":' + datajson + ',"sign":"' + _sign + '","source":"weipro","timeStamp":' + _time + '}')
//   wx.request({
//     url: app.globalData.APIUrl +'/svc/api/Comment/addComment', //仅为示例,并非真实的接口地址     
//     data: {
//       paramJson: '{"data":' + datajson + ',"sign":"' + _sign + '","source":"weipro","timeStamp":' + _time + '}'
//     },
//     header: {
//       'content-type': 'application/x-www-form-urlencoded' // 默认值
//     },
//     method: 'POST',
//     success: function (res) {
//       if (res.data.status == 'SUCCESS') {
//         // console.log(res);  
//         if (imagesUrls != '') {
//           compression(imagesUrls)
//         }
        
//         wx.showToast({
//           title: '评论成功',
//           icon: 'success',
//           duration: 2000,
//           success: function () {
//             setTimeout(function () {
//               //要延时执行的代码
//               wx.switchTab({
//                 url: '../myindex/myindex'
//               })
//             }, 2000) //延迟时间
//           }
//         })
//       }
//     },
//     fail: function (res) {
//     }
//   })

// }

//排序的函数
function objKeySort(arys) {
  //先用Object内置类的keys方法获取要排序对象的属性名,再利用Array原型上的sort方法对获取的属性名进行排序,newkey是一个数组
  var newkey = Object.keys(arys).sort();
  //console.log('newkey='+newkey);
  var newstr =''
  for (var i = 0; i < newkey.length; i++) {
    var str = newkey[i] + arys[newkey[i]];
    newstr+=str;
  }
  return newstr;
}

// module.exports.addcompressionimg = addcompressionimg
// module.exports.addComment = addComment
module.exports.uptokencallback = uptokencallback

具体代码实现

// pages/evaluateOrder/evaluateOrder.js
var utiltime = require('../../../../utils/time.js')
var utilsign = require('../../../../utils/getsign.js')
var httpclient = require('../../../../utils/httpclient.js')
var publish = require('publishashx.js')
const qiniuUploader = require("../../../../utils/qiniuUploader.js");
var app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    productList:[],
    // 上传图片
    imageList: [],
    countIndex:0,
    count: [],
    img: '',
    pics: [],
    paths: [],
    index: 0,
    text:'',
    imgUrl: app.globalData.imgUrl  //图片地址
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // console.log(options)
    var that=this;
    that.setData({
      goodsId: options.goodsid,
      orderId: options.orderid
    })
    var userId = wx.getStorageSync('wxuserid');
    var arys = {
      'goodsId': options.goodsid,
      'orderId': options.orderid,
      'userId': userId
    };
    httpclient.doRequestService('/svc/api/order/getOrderDeatil2', arys, function (res) {
      if (res.status == "SUCCESS") {
        that.setData({
          productList:res.data
        })
      }
    }, null, null)

    
  },

  //textarea
  text:function(e){
    // console.log(e)
    var that=this;
    that.setData({ text: e.detail.value})
  },


  // 上传图片
  choose: function () {
    var that = this,
      pics = this.data.pics;
    that.setData({
      index: 0
    })
    wx.chooseImage({
      sizeType: ['original', 'compressed'], // original 原图,compressed 压缩图,默认二者都有
      sourceType: ['album', 'camera'], // album 从相册选图,camera 使用相机,默认二者都有
      count: 3 - that.data.imageList.length,
      success: function (res) {
        var filePath = res.tempFilePaths;
        if ((filePath.length + that.data.imageList.length) > 3) {
          wx.showToast({
            title: '最多上传3张图片',
            icon: 'none',
            duration: 1000,
            mask: true
          })
        } else {
          var pathsTmp = []
          for (let i = 0; i < filePath.length; i++) {
            // console.log('开始循环')

            var _time = utiltime.getTimems();
            var suiji = Math.floor(Math.random() * 1000)

            var year = new Date().getFullYear();
            var month = new Date().getMonth() + 1;
            var day = new Date().getDate();
            var path = year + '/' + month + '/' + day + '/' + _time + suiji + '.jpg';
            pathsTmp = pathsTmp.concat(path)
          }

          that.setData({
            pics: filePath,
            paths: pathsTmp
          });

          that.uplaod(that, pathsTmp, filePath)
        }

      }
    })

  },
  uplaod: function (self, paths, filePaths) {
    var that = self;
    var imageListtmp = that.data.imageList;
    // console.log(that.data.imageList)
    var i = that.data.index

    publish.uptokencallback(paths[i], function (res2) {
      var upToken = res2.data.upToken

      qiniuUploader.upload(filePaths[i], (res) => {
        // console.log('执行一次 上传')
        // console.log(res.imageURL)
        imageListtmp = imageListtmp.concat(res.imageURL);
        that.setData({
          imageList: imageListtmp,
        })

        i = i  
                       
                    
                    

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap