1、需求php
微信網頁中實現上傳頭像,用戶信息,用戶宣傳照的功能。html
2、問題ajax
微信網頁上傳普通瀏覽器的上傳不同,微信內置瀏覽器禁止了普通的input上傳功能,而且此標籤在有些移動終端顯示不佳。數據庫
3、解決json
使用微信官方文檔提供的jssdk的上傳圖片接口。微信本身的jssdk裏面的圖片上傳不用考慮兼容性。api
具體實現邏輯是:瀏覽器
配置好jssdk後,能夠使用jssdk上傳接口上傳圖片到微信服務器,微信服務器會返回給你一個資源id,咱們在使用js異步或者表單同步把資源id傳輸到php服務器端,php服務器端就利用微信的多媒體下載文件接口再次請求微信服務器得到圖片,而後保存到服務器上。服務器
下面的一個異步上傳,並能夠上傳後顯示圖片的實現代碼:微信
wx.ready(function () {cookie
// 5 圖片接口
// 5.1 拍照、本地選圖
var images = {
localId: [],
serverId: [],
};
document.querySelector('#chooseImage').onclick = function () {
//選擇圖片後開始異步上傳到微信服務器,在syncUpload中接受微信服務器返回的資源id,組合後uploadserverid異步上傳到服務器,服務器處理後返回圖片的路徑,客戶端js接受圖片路徑後組合成html,動態插入。
wx.chooseImage({
success: function (res) {
images.localId = res.localIds;
len = images.localId.length;
syncUpload(images.localId);
}
});
};
//異步上傳圖片到微信服務器
var syncUpload = function(localIds){
var localId = localIds.shift();
wx.uploadImage({
localId: localId,
isShowProgressTips: 1,
success: function (res) {
images.serverId.push(res.serverId);// 返回圖片的服務器端ID
if(len==images.serverId.length){
//異步上傳圖片id到服務器
var serverids = images.serverId.join(',');
/*alert(serverids);*/
uploadserverid(serverids);
//銷燬數據
images.localId = images.serverId = [];
}
//其餘對serverId作處理的代碼
if(localIds.length > 0){
syncUpload(localIds);
}
},
error: function(){
alert("asasasas");
}
});
};
//異步上傳圖片id到服務器,服務器返回真正的圖片地址,js組裝後顯示在頁面上
var uploadserverid = function(serverId){
$.ajax({
url: "./index.php?m=Signup&a=upload",
type: "GET",
data: "serverid="+serverId,
success: function(msg){
if(msg==''){
alert("上傳失敗,請重試");
}
//拼接html
htmlpin(msg);
},
error:function(){
alert("上傳失敗,請重試");
}
});
}
var htmlpin = function(msg){
//拼接圖片html,顯示在頁面
var html = '';
for (var i =0; i<=msg.length - 1; i++) {
html += '<div class="col-xs-3 text-center"> <img class="img-responsive" src="./public/'+ msg[i]+'"> </div>';
};
$('.photo-b').html($('.photo-b').html() + html);
var values = $('#hiddenimages').val();
if(values!=''){values+=',';}
$('#hiddenimages').val(values + msg.join(','));
/* alert($('#hiddenimages').val());*/
}
}
服務器端:
根據微信文檔描述,先得到access_token,而後根據token和資源id得到圖片;注意:由於access_token天天的獲取數量有限制,因此最好獲取後保存到數據庫中。而且access_token的長度是500多,因此要保證數據庫字段的長度夠用。
public function get_access_token(){
$tokenmodel = M('access_token');
$data = $tokenmodel->limit(1)->find();
/*if($data && $data['Expires_In']>time()){
return $data['Access_Token'];
}*/
$url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$this->AppID.'&secret='.$this->AppSecret;
$html = file_get_contents($url);
$json = json_decode($html,true);
$tokenmodel->where('1')->delete();
$tokenmodel->add(array('Access_Token'=>$json['access_token'], 'Expires_In'=>intval($json['expires_in'])+time()));
return $json['access_token'];
}
//從微信服務器上獲取媒體文件
public function get_media($access_token, $media_id){
$url = 'https://api.weixin.qq.com/cgi-bin/media/get?access_token='.$access_token.'&media_id='.$media_id;
$content = file_get_contents($url);
return $content;
}
//根據serverid從微信服務器得到圖片並存儲
public function upload(){
$serverid = I('get.serverid');
$serverids = explode(',', $serverid);
$wechatmodel = D('Wechat');
$flag = true;
foreach ($serverids as $key => $value) {
// M('images')->add(array('Sid'=>'12', 'ImagePath'=>$value));
$content = $wechatmodel->get_media($wechatmodel->get_access_token(), $value);
$imgname = getRandChar(7).'.jpg';
file_put_contents(realpath("./public/") . '/'.$imgname, $content);
/* $open_id = cookie('xiu');*/
/* if($open_id=='og0Q7s_Diefeni0_2vPfN_Tauc3Q'){*/
if($flag){
$flag = false;
//引入圖片處理庫
import('ORG.Util.Image.ThinkImage');
//使用GD庫來處理1.gif圖片
$img = new ThinkImage(THINKIMAGE_GD, "./public/$imgname");
//原圖寬
$oldwidth = $img->width();
$oldheight = $img->height();
if($oldwidth>$oldheight){
$new = $oldheight;
}else{
$new = $oldwidth;
}
//將圖片裁剪爲440x440並保存爲corp.gif
$img->crop($new, $new)->save("./public/thumbs/$imgname");
}
/* }*/
$imgnames[] = $imgname;
}
$this->ajaxReturn($imgnames);
}
原文地址:http://www.daydaytc.com/php/847.html