微信jssdk,實現多圖上傳的一點心得

一.首先在common.js裏封裝一個函數,在須要調用jsSDK的頁面引用此方法便可實現微信的信息配置
function signatureJSSDK() {
var url = window.location.href.split('#')[0];//後臺須要此頁面的url來生成參數
$.ajax({
url:IPWeiXinJssdk,//調用後臺接口,用後臺返回的結果來進行微信接口的基礎配置
type:"post",
dataType:"json",
data:{"url":url},
success:function (result) {
if (result) {
         //後臺接口調用成功,開始配置微信
wx.config({
debug : false, // 開啓調試模式,調用的全部api的返回值會在客戶端alert出來,若要查看傳入的參數,能夠在pc端打開,參數信息會經過log打出,僅在pc端時纔會打印。
appId : result.appid, // 必填,公衆號的惟一標識
timestamp : result.timestamp, // 必填,生成簽名的時間戳
nonceStr : result.noncestr, // 必填,生成簽名的隨機串
signature : result.signature,// 必填,簽名,見附錄1
jsApiList : [// 必填,須要使用的JS接口列表,全部JS接口列表見附錄2
/*
* 全部要調用的 API 都要加到這個列表中
* 這裏以圖像接口爲例
*/
"chooseImage",
"previewImage",
"uploadImage",
"downloadImage" ]
});
}
}
})
}
//微信配置失敗會執行wx.error函數
wx.error(function(res) {
confirmBox2("wx.config.error");
console.log(res);
});
 
二.在須要使用微信多圖上傳的頁面編寫以下代碼
$(function () {
signatureJSSDK();//微信jssdk配置
// config信息驗證失敗會執行error函數,如簽名過時致使驗證失敗,具體錯誤信息能夠打開config的debug模式查看,
// 也能夠在返回的res參數中查看,對於SPA能夠在這裏更新簽名。
wx.ready(function() {//微信配置成功執行此函數
         //localIdsArr 用來存放localIds,serverIdsArr用來存放serverIds
            var localIdsArr = [];var serverIdsArr = [];
            $(".BImgContent").click(function () {//點擊事件觸發微信拍照
var that = $(this);
wx.chooseImage({//調用微信拍照功能
count: 1, // 默認9
sizeType: ['compressed'], // 能夠指定是原圖仍是壓縮圖,默認兩者都有
sourceType: ['camera'], // 能夠指定來源是相冊仍是相機,默認兩者都有
success: function(res) {
localIds = res.localIds; // 返回選定照片的本地ID列表,localId能夠做爲img標籤的src屬性顯示圖片
$(that).find(".ago").attr('src', localIds);//本地預覽,localIds能夠當作img標籤的src屬性
wx.uploadImage({//用戶預覽的同時,上傳至微信服務器
localId:""+localIds,
success: function(res) {
var i =0;
if($(that).hasClass("img1")){
i = 1;
}else if($(that).hasClass("img2")){
i = 2;
}else if($(that).hasClass("img3")){
i = 3;
}
localIdsArr[i] = localIds;//將此圖片的localIds存入數組
serverIdsArr[i] = res.serverId;//將此圖片在微信服務器上的werverID存入數組
}
});
}
});
});
$("#nextStep").click(function () {//用戶點擊下一步時,調用後臺接口,傳給後臺serverIdsArr,後臺可經過此id從微信服務器下載這些圖片到後臺
var flag = 0;
$(".ago").each(function (index,val) { //判斷前臺頁面須要上傳的部分是否都上傳完
var localIds = $(val).attr("src");
if(localIds === "./img/photoAddContent1.png"){
flag = 1;
return false;
}
});
if(flag === 0){//驗證經過,傳送serverID至後臺
// alert("開始發送serverID至後臺");
$(this).unbind("click");
for(var i=0;i<serverIdsArr.length;i++){
pushSeverId(serverIdsArr[i]);
}
}else{
confirmBox2("請完善以上資料");
}
});
});
//將serverId發至後臺,後臺從微信服務器下載圖片,而後反饋圖片在咱們服務器上的相對路徑
var urlList = [];
function pushSeverId(serverId) {
$.post('http://XXX.XXX', { serverId: serverId },function (text, status) {
var obj = {"imgStr":"","imgType":""};
obj.imgStr = text;//text爲後臺返回的圖片url
urlList.push(obj);
// alert(JSON.stringify(urlList));//能夠在手機上打印此數組,調試用,看看是否所有上傳成功
});
}
})
 
  以上是我在使用微信jssdk,實現多圖上傳的代碼,由於每一個人的需求不盡相同,有的部分代碼被我刪除,但願能幫到你們!
相關文章
相關標籤/搜索