微信小程序上传文件或图片(包含base64)至七牛云

微信小程序上传文件或图片(包含base64)至七牛云

  • 上传文件或图片至七牛云
    qiniuUploader.js 文件源码如下
// created by gpake
(function() {

var config = {
    qiniuUploadURL: '',
    qiniuImageURLPrefix: '',
    qiniuUploadToken: '',
    qiniuUploadTokenURL: '',
    qiniuUploadTokenFunction: null
}

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

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


function updateConfigWithOptions(options) {
    if (options.uploadURL) {
        config.qiniuUploadURL = options.uploadURL;
    } else {
        console.error('qiniu uploader need uploadURL');
    }
    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;
    }
}

function upload(filePath, success, fail, options) {
    if (null == filePath) {
        console.error('qiniu uploader need filePath to upload');
        return;
    }
    if (options) {
        init(options);
    }
    if (config.qiniuUploadToken) {
        doUpload(filePath, success, fail, options);
    } else if (config.qiniuUploadTokenURL) {
        getQiniuToken(function() {
            doUpload(filePath, success, fail, options);
        });
    } else if (config.qiniuUploadTokenFunction) {
        config.qiniuUploadToken = config.qiniuUploadTokenFunction();
    } else {
        console.error('qiniu uploader need one of [uptoken, uptokenURL, uptokenFunc]');
        return;
    }
}

function doUpload(filePath, success, fail, options) {
    var url = config.qiniuUploadURL;
    var fileName = filePath.split('//')[1];
    if (options && options.key) {
        fileName = options.key;
    }
    var formData = {
        'token': config.qiniuUploadToken,
        'key': fileName
    };
    wx.uploadFile({
        url: url,
        filePath: filePath,
        name: 'file',
        formData: formData,
        success: function (res) {
            var dataString = res.data
            var dataObject = JSON.parse(dataString);
            //do something
            var imageUrl = config.qiniuImageURLPrefix + dataObject.key;
            dataObject.imageURL = imageUrl;
            console.log(dataObject);
            success(dataObject);
        },
        fail: function (error) {
            console.log(error);
            fail(error);
        }
    })
}

function getQiniuToken(callback) {
  wx.request({
    url: config.qiniuUploadTokenURL,
    success: function (res) {
      var token = res.data.uptoken;
      config.qiniuUploadToken = token;
      if (callback) {
          callback();
      }
    },
    fail: function (error) {
      console.log(error);
    }
  })
}

})();

将上面文件放进小程序中,在需要上传的页面引入

import qiniuUploader from "../../common/qiniuUploader"

上传: 可选择上传文件或上传图片 文件是去联系人里面查找
上传之前需要先请求上传token

  clickUpload() {
    var that = this
    request({
      url: 'api/uploadFiles',
      data:{}
    }).then((res)=> {
      console.log(res)
      that.setData({
        upToken: res.data
      })
    wx.showActionSheet({
      itemList: ["上传图片", "上传文件"],
      success: function(e) {
        if(e.tapIndex==1) {
          // 上传文件
          wx.chooseMessageFile({
            count: 1,
            type: 'file',
            success:function(ress) {
              var url = ress.tempFiles[0].path,
              name = ress.tempFiles[0].name
              qiniuUploader.upload(url, (res) => {
                console.log(res.imageURL)
               // 获取到返回地址
              }, (error) => {
                console.log('error: ' + error);
              }, {
                region: 'ECN',  
                domain: '', // 自己的域名
                uploadURL:'https://up-z2.qiniup.com',//上传地址 ,我这里用的是对应的华南地址
                key: String(new Date().getTime())+Math.floor(Math.random()*50 + 50)+'.'+name, // 上传到七牛云图片就是这名字了
                uptoken: that.data.upToken, // 由其他程序生成七牛 uptoken
              });
            }
          })
        } else {
          wx.chooseImage({
            count: 1,
            success:function(ress) {
              var url = ress.tempFilePaths[0],
              fileSuf = 'png'
              if (url.indexOf('jpeg')>-1) {
                fileSuf = 'jpeg'
              }
              if (url.indexOf('jpg')>-1) {
                fileSuf = 'jpg'
              }
              qiniuUploader.upload(url, (res) => {
              // 获取到图片返回地址
              }, (error) => {
                console.log('error: ' + error);
              }, {
                region: 'ECN',  
                domain: '', // 自己的域名
                uploadURL:'https://up-z2.qiniup.com',
                key: String(new Date().getTime())+Math.floor(Math.random()*50 + 50)+'.'+fileSuf, // 上传到七牛云图片就是这名字了
                uptoken: that.data.upToken, // 由其他程序生成七牛 uptoken
              });
            }
          })
        }
      }
    })
    })
  },

node请求token代码
我这里是将下面代码单独放在upload.js文件中然后返回前端的时候引入的
需要安装qiniuyun sdk
npm install qiniu

const qiniu = require('qiniu');
const formidable = require('formidable');
const fs = require('fs');
const config = {};
config.accessKey = ''; //七牛云Ak密匙
config.secretKey = ''; //七牛云Sk密匙
config.bucket = ''; //存储空间的名字
config.url = ''; //配置的域名
const qn = {}
//构建上传策略函数 (获取七牛上传token)
qn.uptoken = function(bucket) {
    const putPolicy = new qiniu.rs.PutPolicy({ scope: config.bucket });
    const accessKey = config.accessKey;
    const secretKey = config.secretKey;
    const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);
    const uploadToken=putPolicy.uploadToken(mac);
    return uploadToken;
}
     
module.exports = qn;

返回给前端

const qn = require("./upload");
router.get("/api/uploadFiles", (req, res) => {
  const upToken = qn.uptoken();
  format({
    res,
    req,
    err: true,
    doc: 0,
    msg1: `成功`,
    data1: upToken,
    msg2: "失败",
  });
});
  • 上传base64图片到七牛云
    将base64直接上传到七牛云 返回图片路径
    (用于生成canvas 因为painter组件生成canvas图片不能用base64)
// 上传base64图片
  upBase64(url) {
    var that = this
    var pic = url
    if(url=='') {
      return
    }
    request({
      url: 'api/uploadFiles',
      data:{}
    }).then((res)=> {
    //同样先获取上传token
      that.setData({
        upToken: res.data
      })
      wx.request({
        url: 'https://upload-z2.qiniup.com/putb64/-1', //这里地址我同样用的华南的 需要改成你对应七牛云地址
        method: 'post',
        data: pic, 
        header: {
          'Content-Type': 'application/octet-stream',
          'Authorization': "UpToken "+that.data.upToken
        },
        success(result) {
            if(result.data.key) {
              //这个key+你的七牛云图片访问域名就是图片的访问路径
            }
        }
      })
    })
  },

如果返回图片路径小程序真机无法显示 多半是白名单问题 需要去小程序后台进行配置!

七牛云上传文档:
参考文档 官方地址
七牛云上传base64:
参考文档 官方地址

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