亲宝软件园·资讯

展开

微信小程序批量上传图片到七牛(推荐)

人气:0

一、引入七牛SDK

具体查看文档

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

二、封装上传方法upload.js

/**
 * 上传函数
 */
const qiniuUploader = require("qiniuUploader");
const request = require("./request.js")
 
// 初始化七牛相关参数
function initQiniu() {
  var options = {
    uploadURL: 'https://up.qiniup.com',
    region: 'ECN', //
    uptokenURL: request.URL + 'qiniu-token?token=' + getApp().globalData.token,
    // uptoken: 'xxxx',
    domain: 'cdn-mpsoft.tujihome.com/',
  };
  qiniuUploader.init(options);
}
 
function upload(filePath, success, fail) {
  initQiniu();
  // 交给七牛上传
  qiniuUploader.upload(filePath, (res) => {
    success(res);
  }, (error) => {
    console.error('error: ' + JSON.stringify(error));
    fail(error);
  });
}
 
 
/**
 * 批量上传
 * @param images
 */
function batchUpload(images) {
  let uplist = []
  for (let index in images) {
    const path = images[index]['url'];
    const key = images[index]['key'];
    let promise = new Promise((resolve, reject) => {
      qiniuUploader.upload(path, (res) => {
        resolve(res.imageURL)
      }, (error) => {
        reject(error)
      },{
        uploadURL: 'https://up.qiniup.com',
        region: 'ECN', //
        uptokenURL: request.URL + 'qiniu-token?token=' + getApp().globalData.token,
        key: key,
        domain: 'cdn-mpsoft.tujihome.com/',
      });
    })
    uplist.push(promise)
  }
  Promise.all(uplist).then((resultList) => {
    console.log(resultList);
    return resultList;
  }, error => {
    console.log(error)
    throw err;
  })
}
 
module.exports = {
  'upload': upload,
  'BatchUpload' : batchUpload,
}

url:文件路径,key:文件名

batchUpload()传入数组,包含文件路径跟文件名,不需要自定义文件名可以修改下,只调用一次初始化方法,

返回值为包含所有文件路径的数组

三、调用

uploadImage(images) {
    var that = this
    var imageURL = [];
    for (var i of images) {
      i.key = 'gclw_' + Date.parse(new Date()) + Math.random() + '.jpg';
    }
 
    try {
      imageURL = upload.BatchUpload(images);
      return imageURL;
    } catch (e) {
      wx.showModal({
        title: '提示',
        content: e,
        showCancel: false,
      })
    }
  },

结果

总结

以上所述是小编给大家介绍的微信小程序批量上传图片到七牛,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论