小程序上传图片到七牛云代码封装,用时只需要引用下就好,百度网盘下载封装代码包,小程序示例项目git下载
小程序生成上传token封装
const Buffer = require(’./buffer/buffer.js’);
const CryptoJS = require(’./copyto/hmac-sha1.js’);
const base64 = require(’./copyto/enc-base64.js’);
这几个包在上面提到的百度网盘下载就好,或者在上面的git项目里复制过去就好
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
}
上传图片封装
// 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下
先获取token,下面代码分开写的函数
const token = require('../utils/qiniu/qntoken.js')//引入封装资源
/获取token按钮也算初始化建议云端取,git项目里面有个post文件夹参考
data: {
url:'',
tokendata: [],//建议云函数获取处理、、测试时可直接写
uptoken: '',//上传凭证
time: Date.parse(new Date()) //时间截
},
//获取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)
},
//上传图片
upload(e) {
// await this.gettoken()//获取token需要用到 不用await记得吧async取消
this.testgettoken()//获取token
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)//调用上传
}
})
},
生成token时要用到的ak,sk,啥的和删除文件获取教程链接
https://blog.csdn.net/qq_21344043/article/details/104111508