通過微信介面上傳圖片並獲取到自己的伺服器
阿新 • • 發佈:2019-02-19
我們需要使用者在企業號上傳圖片後,該圖片儲存在我們自己的資料庫裡。
所以我們要用到微信JSSDK中的“拍照或選擇手機相簿照片”、“上傳圖片介面”以及“獲取臨時素材介面”。
一開始以為有了media_id就用CURL去請求“獲取臨時素材介面”然後他返回圖片的內容(估計是一堆亂碼),最後自己解釋出來儲存到資料庫。但請求來請求去沒看到他返回文件說的這些東西:
{ HTTP/1.1 200 OK Connection: close Content-Type: image/jpeg Content-disposition: attachment; filename="MEDIA_ID.jpg" Date: Sun, 06 Jan 2013 10:20:18 GMT Cache-Control: no-cache, must-revalidate Content-Length: 339721 Xxxx }
弄了很久,還以為介面沒給我返回東西,原來是CURL那裡設定的時候要設定成:
curl_setopt ($ch, CURLOPT_HEADER, 1);
這樣才會顯示返回頭!裡面就會包含影象的編碼!其實就是一堆亂碼!但後來發現直接使用PHP就可以將它下載到伺服器上……一下是正確流程:
1.使用“拍照或選擇手機相簿照片”、“上傳圖片介面”,返回serverId(即media_id)。
2.前端拿到serverId(即media_id)後,將此作為引數去請求後臺“獲取臨時素材介面”var images = { localId: [], serverId: [] }; wx.chooseImage({ success: function(res) { images.localId = res.localIds; alert('已選擇 ' + res.localIds.length + ' 張圖片'); if (images.localId.length == 0) { alert('請先使用 chooseImage 介面選擇圖片'); return; } var i = 0, length = images.localId.length; images.serverId = []; function upload() { wx.uploadImage({ localId: images.localId[i], success: function(res) { i++; alert('已上傳:' + i + '/' + length); images.serverId.push(res.serverId); if (i < length) { upload(); } }, fail: function(res) { alert(JSON.stringify(res)); } }); } upload(); } });
//根據微信JS介面上傳了圖片,會返回上面寫的images.serverId(即media_id),填在下面即可 $str = "https://qyapi.weixin.qq.com/cgi-bin/media/get?access_token=''&media_id=''"; //獲取微信“獲取臨時素材”介面返回來的內容(即剛上傳的圖片) $a = file_get_contents($str); //__DIR__指向當前執行的PHP指令碼所在的目錄 echo __DIR__; //以讀寫方式開啟一個檔案,若沒有,則自動建立 $resource = fopen(__DIR__."/1.jpg" , 'w+'); //將圖片內容寫入上述新建的檔案 fwrite($resource, $a); //關閉資源 fclose($resource);