以下分享筆者在項目中使用微信 JS-SDK 實現多圖片上傳的完整思路與代碼。
首先在公共文件中封裝一個函數,任何需要調用 JS-SDK 的頁面只要引用它,即可完成微信的信息配置:
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, //是否開啟調試模式 appId : result.appid, //必填,公眾號的唯一標識 timestamp : result.timestamp, //必填,生成簽名的時間戳 nonceStr : result.noncestr, //必填,生成簽名的隨機串 signature : result.signature, //必填,簽名 jsApiList : [ //必填,需要使用的 JS 接口列表 "chooseImage", "previewImage", "uploadImage", "downloadImage" ] }); } } }) } //微信配置失敗會執行 wx.error 函數 wx.error(function(res) { confirmBox2("wx.config.error"); console.log(res); });
在需要使用微信多圖上傳的頁面中,編寫如下代碼:
$(function () { signatureJSSDK(); //微信 jssdk 配置 //config 信息驗證失敗會執行 error 函數,如簽名過期,可打開 debug 模式查看 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 列表 $(that).find(".ago").attr('src', localIds); //本地預覽 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; //將此圖片在微信服務器上的 serverId 存入數組 } }); } }); }); $("#nextStep").click(function () { //用戶點擊下一步時,將 serverIdsArr 傳給後台 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 至後台 $(this).unbind("click"); for(var i=0;i<serverIdsArr.length;i++){ pushSeverId(serverIdsArr[i]); } }else{ confirmBox2("請完善以上資料"); } }); }); //將 serverId 發至後台,後台從微信服務器下載圖片並返回其在我們服務器上的相對路徑 var urlList = []; function pushSeverId(serverId) { $.post('https://XXX.XXX', { serverId: serverId }, function (text, status) { var obj = {"imgStr":"","imgType":""}; obj.imgStr = text; //text 為後台返回的圖片 url urlList.push(obj); }); } })
以上便是筆者使用微信 JS-SDK 實現多圖上傳的完整代碼。由於每個人的需求不盡相同,部分代碼已做刪減,希望能給大家帶來參考。