小程序对七牛云文件上传删除批量删除生成token封装无需服务器一个小程序搞定

微信小程序获取token接入七牛云上传删除批量删除图片封装亲测可用

小程序获取七牛云uptoken删除文件封装

在研究官方文档后自己用小程序生成uptoken上传凭证封装,其他资料都说要服务器我又没钱只是一个爱好者于是乎就用小程序云开发完成,数据存在小程序云数据库自有自己可访问,记得小程序云端创建记录加上_openid,用于权限识别微信自动根据它识别你设置的权限,思路云函数生成token存入云数据库 ,然后小程序调用,下面我用的是本地生成(不建议不安全,主要是讲方法)本地生成uptoken 需要引入的包百度网盘链接项目片段代码下载:git地址

七牛云获取ak、sk、bkt、cdn

ak,sk,是秘钥,bkt,是空间名,cdn是测试域名,进入七牛云,对象存储,你就能看到你的空间名,右上角点头像,秘钥,就能看到aksk
在这里插入图片描述在这里插入图片描述在这里插入图片描述
点击空间名就能看到cdn
在这里插入图片描述

本地生成uptoken封装的

const Buffer = require('./buffer/buffer.js');
const CryptoJS = require('./copyto/hmac-sha1.js');
const base64 = require('./copyto/enc-base64.js');



function base64ToUrlSafe(v) {
  return v.replace(/\//g, '_').replace(/\+/g, '-');
};

function token(opt) {
  var  accessKey = opt.ak;
  var secretkey = opt.sk;
  var bucket=opt.bkt;
  var  strdata={
    "scope": bucket,//空间域名
    "deadline": Date.parse(new Date()) //当前时间截
  }
  wx.setStorageSync('tokentime', strdata.deadline)
  var str = JSON.stringify(strdata);
  var encoded = Buffer.from(str).toString('base64');
  console.log('base64', encoded)
  var encodedStr = base64ToUrlSafe(encoded);
  console.log('encodedStr', str,encodedStr)
//HmacSHA1加密

  var sign = CryptoJS.HmacSHA1(encodedStr, secretkey);
  console.log('sign',sign)
  var cod = base64.stringify(sign)
  console.log('cod',cod)
  var encodedSign = base64ToUrlSafe(cod);
  var token = accessKey + ':' + encodedSign + ':' + encodedStr;
  console.log('token', token)
  return token;
};


exports.hmacSha1 = function (encodedFlags, secretKey) {
  /*
 *return value already encoded with base64
 * */
  var hmac = crypto.createHmac('sha1', secretKey);
  hmac.update(encodedFlags);
  return hmac.digest('base64');
};

module.exports = {
  token:token
}

删除单个文件


const Buffer = require('./buffer/buffer.js');
const CryptoJS = require('./copyto/hmac-sha1.js');
const base64 = require('./copyto/enc-base64.js');

function base64ToUrlSafe(v) {
  return v.replace(/\//g, '_').replace(/\+/g, '-');
};

function delet(e,cb) {
  var secretkey = e.sk;  //你的sk
  var accessKey = e.ak;  //你的ak
  var bucket = e.bkt //你的空间名
  var cdn = e.cdn //CDN 测试域名
  var filename = e.filename//要删除的文件名
  var str = bucket + ':' + filename.split( cdn + '/')[1];
  var encoded = Buffer.from(str).toString('base64'); //字符串64编码
  var encodedEntryURI = base64ToUrlSafe(encoded);  //安全编码就是替换掉一些符号看
  console.log('encodedEntryURI', str, encodedEntryURI)

  var signingStr = '/delete/' + encodedEntryURI + '\n'
  var sign = CryptoJS.HmacSHA1(signingStr, secretkey); //HmacSHA1签名
  var cod = base64.stringify(sign);  //HmacSHA1的64编码
  var encodedSign = base64ToUrlSafe(cod);
  //拼接accessToken
  var accessToken = accessKey + ":" + encodedSign
  //请求接口
  wx.request({
    url: "http://rs.qbox.me/delete/" + encodedEntryURI,
    method: "POST",
    header: {
      "Content-Type": "application/x-www-form-urlencoded",
      "Authorization": 'QBox ' + accessToken
    },
    success: function (res) {
      return typeof cb == "function" && cb(res.data) //更具返回数据判断
      console.log(res.data);
      wx.showToast({
        title: '删除成功!',
        icon: 'success',
        duration: 2000
      })
    },
    fail: function () {
      return typeof cb == "function" && cb(false)
    }
  })
};

module.exports = {
  delet: delet
}

批量删除文件


const Buffer = require('./buffer/buffer.js');
const CryptoJS = require('./copyto/hmac-sha1.js');
const base64 = require('./copyto/enc-base64.js');
const querystring = require('./querystring/encode.js');
function base64ToUrlSafe(v) {
  return v.replace(/\//g, '_').replace(/\+/g, '-');
};

function delet(e, cb) {
  var secretkey = e.sk;  //你的sk
  var accessKey = e.ak;  //你的ak
  var bucket = e.bkt //你的空间名
  var cdn = e.cdn //CDN 测试域名
  var filename = e.filename//要删除的文件名
  var opa=[]
  for (let i = 0; i < filename.length;i++){
    var str = bucket + ':' + filename[i].split(cdn + '/')[1];
    var encoded = Buffer.from(str).toString('base64'); //字符串64编码
    var encodedEntryURI = base64ToUrlSafe(encoded);  //安全编码就是替换掉一些符号看
    var signingStr = '/delete/' + encodedEntryURI
    opa.push(signingStr)
  }
   let op=''
   for (let i = 0; i < opa.length; i++){
     var  opp = 'op=' + opa[i]
     if (i < opa.length-1){
       op += opp + '&'
     }else{
      op += opp
     }  
   }
  var signingStr = '/batch?' + op + '\n'
  var sign = CryptoJS.HmacSHA1(signingStr, secretkey); //HmacSHA1签名
  var cod = base64.stringify(sign);  //HmacSHA1的64编码
  var encodedSign = base64ToUrlSafe(cod);
  //拼接accessToken
  var accessToken = accessKey + ":" + encodedSign
  //请求接口
  wx.request({
    url: "http://rs.qbox.me/batch?"+op,
    method: "post",
    header: {
      "Content-Type": "application/x-www-form-urlencoded",
      "Authorization": 'QBox ' + accessToken
    },
    success: function (res) {
      return typeof cb == "function" && cb(res.data) //更具返回数据判断
      console.log(res.data);
      wx.showToast({
        title: '删除成功!',
        icon: 'success',
        duration: 2000
      })
    },
    fail: function () {
      console.log('删除失败')
      return typeof cb == "function" && cb(false)
    }
  })
};

module.exports = {
  delet: delet
}

上传文件

// created by gpake
(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, before, complete) {
    if (null == filePath) {
        console.error('qiniu uploader need filePath to upload');
        return;
    }
  console.log('options',filePath,options)
    if (options) {
      updateConfigWithOptions(options);
    }
    if (config.qiniuUploadToken) {
        doUpload(filePath, success, fail, options, progress, cancelTask, before, complete);
    } else if (config.qiniuUploadTokenURL) {
        getQiniuToken(function() {
            doUpload(filePath, success, fail, options, progress, cancelTask, before, complete);
        });
    } 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, before, complete);
    } else {
        console.error('qiniu uploader need one of [uptoken, uptokenURL, uptokenFunc]');
        return;
    }
}

function doUpload(filePath, success, fail, options, progress, cancelTask, before, complete) {
    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
    }
    before && before();
    var uploadTask = wx.uploadFile({
        url: url,
        filePath: filePath,
        name: 'file',
        formData: formData,
        success: function (res) {
          var dataString = res.data
        //   // this if case is a compatibility with wechat server returned a charcode, but was fixed
        //   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 fileUrl = config.qiniuImageURLPrefix + '/' + dataObject.key;
            dataObject.fileUrl = fileUrl
            dataObject.imageURL = fileUrl;
            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);
            }
        },
        complete: function(err) {
            complete && complete(err);
        }
    })

    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.qiniup.com'; break;
        case 'NCN': uploadURL = 'https://up-z1.qiniup.com'; break;
        case 'SCN': uploadURL = 'https://up-z2.qiniup.com'; break;
        case 'NA': uploadURL = 'https://up-na0.qiniup.com'; break;
        case 'ASG': uploadURL = 'https://up-as0.qiniup.com'; break;
        default: console.error('please make the region is with one of [ECN, SCN, NCN, NA, ASG]');
    }
    return uploadURL;
}

})();

引用代码.js

const app = getApp()
const token = require('../utils/qiniu/qntoken.js')
const qiniuUploader = require("../utils/qiniu/qiniuUploader.js");
const qiniudelete = require('../utils/qiniu/qianniudelete.js')
Page({
  data: {
    url:'http://q3hsi9s02.bkt.clouddn.com/tmp/touristappid.o6zAJs9PGSG4t0J-RnpDxkuKxbWw.8xVI1cVSSOmD9a7323c4f2e3b204e02d6aede131281a.png',
    tokendata: [],//建议云函数获取处理、、测试时可直接写
    uptoken: '',//上传凭证
    time: Date.parse(new Date()) //时间截
  },
  onLoad: function () {
    //this.query_qiniudata()获取云端tokendata
    
  },

//测试获取token按钮
  testgettoken(){
    var tokendata=[]
    tokendata.ak ='你的ak'
    tokendata.sk = '你的'
    tokendata.bkt = '你的空间名'
    tokendata.cdn = '你的测试cdn'

    this.data.tokendata = tokendata
    var uptoken = token.token(tokendata)  
this.setData({
  uptoken: uptoken
})
    console.log('uptoken', uptoken,this.data.tokendata)
  },

//测试删除按钮
dele(){
  var sendtokendata = this.data.tokendata //提前配置
  sendtokendata.filename = this.data.url;//删除用的
  console.log('sendtokendata')

  qiniudelete.delet(sendtokendata)//调用删除
  this.setData({
    url: this.data.url,
    time: Date.parse(new Date())
  })
},

//测试批量删除
batchdele(){
  var file_Name = ['http://s02.bkt.clouddn.com/tmp/wx9eakuKxbWw.85Ic4XUa06103e01320.jpg', 'http://02.bkt.clouddn.com/tmp/wx9ea6e64enpDxkuKxbWw.8BwWCdMtm6hj4d8d0e47ff1de050c814f7.jpg']//数据删除了写填你的

  this.data.tokendata.fileName = file_Name
  console.log('传输tokendata', this.data.tokendata)

  batchdelete.delet(this.data.tokendata)//调用批量删除
},
//上传图片
   upload(e) {
   // await this.gettoken()//获取token需要用到 不用await记得吧async取消
    
    console.log(e)//传入的地址
    wx.showLoading({
      title: '上传中',
    })
    var that = this
    qiniuUploader.upload(
      e, //上传的图片
      (res) => {  //回调 success
        let url = 'http://' + res.imageURL;
        that.setData({
          url: url,
        })
        console.log(res,url);
      },
      (error) => { //回调 fail
        console.log('error: ' + error);
      },
      {
        // 参数设置  地区代码 token domain 和直传的链接 注意七牛四个不同地域的链接不一样,我使用的是华南地区
        region: 'SCN',
        // ECN, SCN, NCN, NA, ASG,分别对应七牛的:华东,华南,华北,北美,新加坡 5 个区域
        uptoken: that.data.uptoken,   //上传凭证自己生成
        uploadURL: 'https://upload-z2.qiniup.com',//下面选你的区z2是华南的
        // case 'ECN': uploadURL = 'https://up.qiniup.com'; break;
        // case 'NCN': uploadURL = 'https://up-z1.qiniup.com'; break;
        // case 'SCN': uploadURL = 'https://up-z2.qiniup.com'; break;
        // case 'NA': uploadURL = 'https://up-na0.qiniup.com'; break;
        // case 'ASG': uploadURL = 'https://up-as0.qiniup.com'; break;
        domain: that.data.tokendata.cdn,    //cdn域名建议直接写出来不然容易出异步问题如domain:‘你的cdn’
      },
      (progress) => {
        if (progress.progress == 100) {
          wx.hideLoading()
        }
        console.log('上传进度', progress.progress)
        console.log('已经上传的数据长度', progress.totalBytesSent)
        console.log('预期需要上传的数据总长度', progress.totalBytesExpectedToSend)
      },
    )
  },
  
  //更换图片
   changeimage(e) {
    let that = this
     if (this.data.uptoken==''){
      wx.showToast({
        title: '先获取token',
      })
      return
    }
    var sendtokendata = this.data.tokendata
    sendtokendata.filename = that.data.url;//删除用
    console.log('sendtokendata')

    qiniudelete.delet(sendtokendata)//调用删除

    var tempimageurl = ''
    wx.chooseImage({
      count: 1,//选一个图
      sizeType: ['original', 'compressed'],//原图压缩图
      sourceType: ['album', 'camera'],//相机相册
      success: function (photo) {
        tempimageurl = photo.tempFilePaths[0];
        console.log(tempimageurl)


        that.upload(tempimageurl)//调用上传


      }
    })
  },

引用代码.wxml

<view class="box"><view class="edit_imagebox" bindtap="changeimage">
<image class="chooseImvadd" src="../images/add.png" mode="scaleToFill"></image>
<!-- +'?v=2020'强制刷新七牛云端数据防止删除链接还可用也可以接当前时间截 -->
<image src="{{ url+'?v='+time }}" class="edit_image" mode='aspectFill' />
<image class="closeImv" src="../images/clear.png" mode="scaleToFill" catchtap="dele"></image>
</view></view>

<button bindtap="testgettoken">1点我获取token</button>
<text>上传凭证uptoken:{{uptoken}}</text>
<button bindtap="dele" style="margin-top: 20rpx;">删除图片</button>

<view class="box">在js输入你的ak//sk/btk空间名//cdn测试域名</view>

建议

百度网盘下载我的封装代码包,和去git下载项目片段,我也是小白只是看了好多文档没这类教程于是在自己做商城时遇到的问题希望可以帮到部分朋友,代码都测试过可以用,自己在美化下就好,同时还做了个狼人杀面杀小程序,搜索小程序范的样,就能找到
在这里插入图片描述
在这里插入图片描述
作者:范的样

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值