jssdk微信图片上传功能

时间:2023-01-22 00:12:57

/*wx.config({
debug: false,
appId: data.appid,
timestamp: data.timestamp,
nonceStr: data.nonceStr,
signature: data.signature,
jsApiList: ['checkJsApi', 'chooseImage', 'previewImage', 'uploadImage', 'downloadImage']
});

wx.ready(function () {
//
});*/

//onclick事件
var images = {
localId: [],
serverId: [],
downloadId: []
};
document.querySelector('#selectImage').onclick = function () {
wx.chooseImage({
success: function (res) {
images.localId = res.localIds;
jQuery(function(){
$.each( res.localIds, function(i, n){
$("#img").append('<img src="'+n+'" /> <br />');
});
});
}
});
};

document.querySelector('#uploadImage').onclick = function () {
if (images.localId.length == 0) {
alert('请先使用选择图片按钮');
return;
}
images.serverId = [];
jQuery(function(){
$.each(images.localId, function(i,n) {
wx.uploadImage({
localId: n,
success: function (res) {
images.serverId.push(res.serverId);
alert(res.serverId);
},
fail: function (res) {
alert(JSON.stringify(res));
}
});
});
});
};

document.querySelector('#downloadImage').onclick = function () {
if (images.serverId.length == 0) {
alert('请先按上传图片按钮');
return;
}
jQuery(function() {
$.each(images.serverId, function (i, n) {
wx.downloadImage({
serverId: n,
success: function (res) {
images.downloadId.push(res.localId);
}
});
});
$.each( images.downloadId, function(i, n){
alert(n);
$("#img2").append('<img src="'+n+'" /> <br />');
});
});
};

document.querySelector('#previewImage').onclick = function () {
var imgList = [
'http://wp83.net__PUBLIC__/images/gallery/image-1.jpg',
'http://wp83.net__PUBLIC__/images/gallery/image-2.jpg'
];
wx.previewImage({
current: imgList[0],
urls: imgList
});
};

//返回错误
wx.error(function(res){
var str = res.errMsg;
var reg = /invalid signature$/;
var r = str.match(reg);
if(r !== null) {
jQuery(function(){
$.getJSON('http://www.demo.com/tp/home/index/ticket', function(data) {
if(data) {
alert('ticket update');
location = location;
window.navigate(location);
}
});
});
}
});