当前位置:主页 > 网页前端 > JavaScript代码 >

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

时间:2022-01-15 10:31:54 | 栏目:JavaScript代码 | 点击:

一、引入七牛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,
      })
    }
  },

结果

总结

您可能感兴趣的文章:

相关文章