第一件事首先是微信的選擇圖片功能,就是微信發朋友圈選擇圖片的時候那個界面
//調用微信拍照功能 wx.chooseImage({ count: 1, // 默認9 sizeType: ['original', 'compressed'], //原圖-壓縮圖 sourceType: ['album', 'camera'], //指定來源是相冊還是相機 success: function (res) { let localIds = res.localIds; syncUpload(localIds); } });
其中syncUpload函數功能為上傳圖片到微信服務器中
var syncUpload = function (localIds) { var localId = localIds.pop(); //上傳圖片 wx.uploadImage({ localId: localId, isShowProgressTips: 1, success: function (res) { // 返回圖片的服務器端ID var serverId = res.serverId; $.ajax({ url: "", data: { media_id: serverId }, success: function (data) { alert("你的圖片路徑地址是:" + data); }, erro: function (erro) { alert(erro); } }) } }); };
中間空着的url地址則是自己的后台處理這個事件的地址
我使用的是C# ,處理代碼如下
if (Request["media_id"]!=null) { string media_id = Request["media_id"].ToString(); string url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token="+ wxHelper2.access_token+ "&media_id="+ media_id; var result = new WebClient(); result.DownloadFile(url, Server.MapPath("/upload/WxImg_" + media_id+".jpg")); string savePath = Server.MapPath("/upload/WxImg_" + media_id + ".jpg"); Response.Write(savePath); Response.End(); }
這樣就可以保存了