微信JS公眾號開發上傳圖片到本地伺服器
阿新 • • 發佈:2019-02-07
微信公眾號開發中一般會涉及到在手機公眾號程式中選擇本地圖片或者拍照,將圖片上傳到本地後臺伺服器的功能,網上的做法一般是呼叫微信官方提供的chooseImage方法,再判斷是android還是ios並且是否使用WKWebview核心,最後再分別處理返回值將之轉為base64編碼的資料,再上傳到伺服器上。
這種辦法的難點在於需要判斷系統,並且對微信返回的資料進行base64編碼,然後在伺服器端還得寫base64解碼的邏輯,本文不使用通用的做法,而是採用先上傳到微信伺服器,再到後臺伺服器端從微信伺服器下載回來儲存到檔案伺服器。具體程式碼如下:
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'); } }); }
先呼叫wx.chooseImage方法來選擇圖片,然後將結果再呼叫上傳圖片的方法wx.uploadImage,拿到上傳成功的返回值就是mediaId,再呼叫我們自己寫的伺服器端的controller方法將mediaId通過ajax提交過去,接下來就是伺服器端的程式碼。
3、伺服器端處理邏輯
/** * 獲取臨時素材 * * @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; //建立請求物件 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方法 }
呼叫downloadMedia方法之後獲取Attachment物件,主要就是對BufferedInputStream物件的fileStream來進行處理,這個屬性就是圖片檔案流,儲存檔案流到本地就有很多的方法,可以使用apache提供的FileUtils類來處理,這裡就不提供具體的程式碼了,網上很多類似的。至此我們就已經成功的實現在微信公眾號上上傳圖片到本地伺服器了。
微信公眾號