這種辦法的難點在于需要判斷系統(tǒng),并且對微信返回的數(shù)據(jù)進行base64編碼,然后在服務(wù)器端還得寫base64解碼的邏輯,本文不使用通用的做法,而是采用先上傳到微信服務(wù)器,再到后臺服務(wù)器端從微信服務(wù)器下載回來保存到文件服務(wù)器。具體代碼如下:
1、頁面
<input type="button" id="uploadBtn">
頁面上只有一個普通的button的上傳按鈕
2、js邏輯
$('#uploadBtn').click(function () { wx.chooseImage({ count: 1, sizeType: ['original', 'compressed'], // 可以指定是原圖還是壓縮圖,默認二者都有 sourceType: ['album', 'camera'], // 可以指定來源是相冊還是相機,默認二者都有 success: function (res) { var localIds = res.localIds; // 返回選定照片的本地ID列表,localId可以作為img標簽的src屬性顯示圖片 that.uploadImg(localIds[0]); } }); }); //具體上傳圖片 uploadImg: function (e) { wx.uploadImage({ localId: e, // 需要上傳的圖片的本地ID,由chooseImage接口獲得 isShowProgressTips: 1, // 默認為1,顯示進度提示 success: function (res) { serverId = res.serverId; $.ajax({ url: "/uploadImg", dataType: "json", async: false, contentType: "application/x-www-form-urlencoded; charset=UTF-8", data: {"mediaId": serverId}, type: "POST", timeout: 30000, success: function (data, textStatus) { $('#imgUrl').val(data); $.toast('上傳成功', 'text'); }, error: function (XMLHttpRequest, textStatus, errorThrown) { $.toast('上傳錯誤,請稍候重試!', 'text'); } }); }, fail: function (error) { $.toast('上傳錯誤,請稍候重試!', 'text'); } }); }
先調(diào)用wx.chooseImage方法來選擇圖片,然后將結(jié)果再調(diào)用上傳圖片的方法wx.uploadImage,拿到上傳成功的返回值就是mediaId,再調(diào)用我們自己寫的服務(wù)器端的controller方法將mediaId通過ajax提交過去,接下來就是服務(wù)器端的代碼。
3、服務(wù)器端處理邏輯
/** * 獲取臨時素材 * * @param mediaId 媒體文件ID * @return 正確返回附件對象,否則返回null * @throws WeixinException */ public Attachment downloadMedia(String mediaId) throws WeixinException { //下載資源 String url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=" + this.oauthToken.getAccess_token() + "&media_id=" + mediaId; //創(chuàng)建請求對象 HttpsClient http = new HttpsClient(); return http.downloadHttps(url); } 其中Attachment表示下載文件返回值對象,包含的屬性有: public class Attachment { private String fileName; private String fullName; private String suffix; private String contentLength; private String contentType; private BufferedInputStream fileStream; private String error; 省略get/set方法 }
調(diào)用downloadMedia方法之后獲取Attachment對象,主要就是對BufferedInputStream對象的fileStream來進行處理,這個屬性就是圖片文件流,保存文件流到本地就有很多的方法,可以使用apache提供的FileUtils類來處理,這里就不提供具體的代碼了,網(wǎng)上很多類似的。至此我們就已經(jīng)成功的實現(xiàn)在微信公眾號上上傳圖片到本地服務(wù)器了。
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com