1.投票報名
主要實現報名功能
(1)form表單佈局javascript
<section class="content"> <div id="errormsg" > </div> <h2>報名處</h2> <form action="" method="post" > <input type="hidden" name="c" value="entry" /> <input type="hidden" value="signup" name="do"> <input type="hidden" value="sign" name="op"> <input type="hidden" value="lb_vote" name="m"> <input type="hidden" name="rid" value="{$id}" /> <div class="form-group"> <label for="exampleInputEmail1">姓名</label> <input type="uname" class="form-control" id="uname" name="uname" placeholder="姓名"> </div> <div class="form-group"> <label for="exampleInputPassword1">手機號</label> <input type="number" class="form-control" id="uphone" name="uphone" placeholder="手機號"> </div> <div class="form-group" > <label for="imgdis">圖片</label> <div class="imageitem"> <div class="upload_image"> <img name="imgdis" id="ImgPr" src=""/> </div> </div> <div> <div class="upload_btn" > <span class="icon-plus"></span> <input type="button" name="file" id="choose" /> </div> </div> </div> <div class="form-group" > <label for="exampleInputPassword1" >描述</label> <textarea class="form-control" name="discription" id="discrption"></textarea> </div> <button type="button" id="sbtn" onclick="subform();" class="form-control btn btn-danger " value="報名">報名</button> </form> </section>
2.js檢驗輸入的正確性php
function checkform(){ var uname=$("#uname").val(); var uphone=$("#uphone").val(); var discrption=$("#discrption").val(); if($("#uname").val()==''){ $("#errormsg").html('用戶名不能爲空!'); // $('#errormsg').delay(5000).hide(0); $("#errormsg").show(2000); $("#errormsg").hide(2000); $("#uname").focus(); return false; } /*驗證手機號的表達式*/ var myphone = /^(((13[0-9]{1})|(14[0-9]{1})|(17[0]{1})|(15[0-3]{1})|(15[5-9]{1})|(18[0-9]{1}))+\d{8})$/; if($("#uphone").val()==''){ $("#errormsg").html('手機號不能爲空'); // $('#errormsg').delay(5000).hide(0); $("#errormsg").show(2000); $("#errormsg").hide(2000); $("#uphone").focus(); return false; }else if(uphone.length!=11){ $("#errormsg").html('請輸入11位手機號碼!'); $("#errormsg").show(2000); $("#errormsg").hide(2000); //$('#errormsg').delay(5000).hide(0); $("#uphone").focus(); return false; }else if(!myphone.test(uphone)){ $("#errormsg").html('請輸入有效的手機號!'); //$('#errormsg').delay(5000).hide(0); $("#errormsg").show(2000); $("#errormsg").hide(2000); $("#uphone").focus(); return false; } // if($("#choose").val()==''){ // $("#errormsg").html('未選者圖片'); // //$('#errormsg').delay(5000).hide(0); // $("#errormsg").show(2000); // $("#errormsg").hide(2000); // $("#upload_image").focus(); // return false; // } if($("#discrption").val()==''){ $("#errormsg").html('簡介爲空!'); $("#errormsg").show(2000); $("#errormsg").hide(2000); $("#discrption").focus(); return false; } return true; }
3.微信JSSDK圖片上傳功能
3.1 jssdk.php jsapi_ticket.php access_token.php 放在項目文件下
3.2獲取wx.config所須要的信息
頁面中添加以下代碼css
<?php $url=dirname(dirname(dirname(dirname(dirname(dirname(dirname(__FILE__))))))); $url=$url.'/addons/lb_vote/jssdk.php'; include $url; $jsdk=new JSSDK('wxa3816b432f7291ba','e469db86bec9661650362dc2f9df8956'); $signPackage = $jsdk->GetSignPackage(); ?>
3.3實現圖片預覽和上傳到微信服務器功能html
<script type="text/javascript"> wx.config({ debug: false, // 開啓調試模式,調用的全部api的返回值會在客戶端alert出來,若要查看傳入的參數,能夠在pc端打開,參數信息會經過log打出,僅在pc端時纔會打印。 appId:'<?php echo $signPackage["appId"];?>', // 必填,公衆號的惟一標識 timestamp:<?php echo $signPackage["timestamp"];?>, // 必填,生成簽名的時間戳 nonceStr: '<?php echo $signPackage["nonceStr"];?>', // 必填,生成簽名的隨機串 signature:'<?php echo $signPackage["signature"];?>',// 必填,簽名,見附錄1 jsApiList: ['chooseImage','previewImage','uploadImage','downloadImage'] // 必填,須要使用的JS接口列表,全部JS接口列表見附錄2 }); var choose=document.getElementById('choose'); /*定義images用來保存選擇的本地圖片ID 和上傳的服務器圖片ID*/ var images={ localId:[], serverId:[], } wx.ready(function(){ var total=5;/*限制上傳的數量*/ var sum=0;/*每次上傳的數量*/ var upsum=0;/*已上傳的總數*/ choose.onclick=function(){ wx.chooseImage({ count:5,/*默認爲9*/ success:function(res){ images.localId=res.localIds;/*保存到images*/ sum=images.localId.length; if((upsum+sum)>total){ var last=total-upsum; alert('你還能夠選擇:'+last+'張'); return false; } /*圖片預覽*/ // wx.previewImage({ // current: res.localIds, // 當前顯示圖片的http連接 // urls: res.localIds // 須要預覽的圖片http連接列表 // }); /*相應位置預覽*/ var count=res.localIds.length+upsum; for(j=upsum;j<count;j++){ if(j==0){ $("#ImgPr").attr('src',res.localIds[0]); }else{ $new=$(".imageitem").last().clone(true); $new.find('img').attr('src',res.localIds[j-upsum]); $new.insertAfter($(".imageitem").last()); } } upsum=upsum+sum; /*上傳圖片到微信服務器*/ var i=0;len=images.localId.length; wxupload(); function wxupload(){ wx.uploadImage({ localId: images.localId[i], // 須要上傳的圖片的本地ID,由chooseImage接口得到 //isShowProgressTips: 1, // 默認爲1,顯示進度提示 success: function (res) { i++; //將上傳成功後的serverId保存到serverid images.serverId.push(res.serverId); if(i < len){ wxupload(); } } }); } /*上傳圖片*/ } } ); } }); /*驗證失敗時執行的函數*/ wx.error(function(res){ alert(res.errMsg); }); </script>
4.圖片上傳到微信服務器之後 提交報名 使用AJAX將表單提交到php文件java
<script type="text/javascript"> function subform(){ if(checkform()){ var str=''; var serverId=images.serverId; for(var i=0;i<serverId.length;i++){ str+='img='+serverId[i]; } $.ajax({ url:"{php echo $this->createMobileUrl('Signup',array('op'=>'sign'))}", type:'post', data:$("form").serialize()+"&imgserverid="+str, dataType:'json', success:function(data){ alert(data.msg); // if(data.success==1){ // // alert("報名成功"); // alert(data); // }else{ // alert(mydata.desc); // } } }); } } </script>
5.php端從微信服務器下載圖片
5.1獲取access_tokenjquery
function getaccesstoken(){ $appId='wxa3816b432f7291ba'; $appSecret='e469db86bec9661650362dc2f9df8956'; $ur="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}"; $chu= curl_init(); curl_setopt($chu, CURLOPT_URL, $ur); curl_setopt($chu, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($chu, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($chu, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($chu); curl_close($chu); $jsoninfo = json_decode($output, true); $access_token = $jsoninfo["access_token"]; /*獲取access_token*/ return $access_token; }
5.2從微信服務器下載圖片ajax
function downlodimg($access_token,$serverId){ $targetName=dirname(dirname(dirname(__FILE__))).'/upload/images/'.rand(1,100).date('YmdHis').'.jpg'; $url="http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id={$serverId}"; $ch=curl_init($url); file_put_contents('urlres.log', $url); $fp=fopen($targetName, 'wb'); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, 0); curl_exec($ch); curl_close($ch); fclose($fp); return $targetName; }
6.完整的PHP報名代碼數據庫
if($op=='sign'){ /*從微信服務器下載圖片*/ if($_POST){ /*往ajax返回json格式數據*/ /*圖片從微信服務器下載到服務器*/ $msgdata=array(); $lbimg=array(); $access_token=getaccesstoken(); file_put_contents('accc.log', $access_token); $mediaid=$_POST['imgserverid']; $media_i=explode('img=', $mediaid); /*去空後的數組*/ $media_id=array(); for($j=0;$j<count($media_i);$j++){ if(!empty($media_i[$j])){ array_push($media_id, $media_i[$j]); } } for($i=0;$i<count($media_id);$i++){ $serverId=$media_id[$i]; $myresult=downlodimg($access_token,$serverId); if(empty($myresult)){ $msgdata['msg']="圖片上傳失敗,請從新上傳!"; }else{ $lbimg[$i]['img']=$myresult; } } /*用戶報名信息插入數據庫*/ /*img轉json格式*/ $imgpath=json_encode($lbimg); $sign_data = array( 'rid' =>$_POST['rid'], 'uniacid' =>intval($_W['uniacid']), 'title'=>strval($_POST['discription']), 'openid'=>strval($_W['openid']), 'nickname'=>strval($_POST['uname']), 'phone'=>strval($_POST['uphone']), 'avatar'=>'', 'pass'=>0, 'sharenum'=>0, 'time'=>time(), 'img'=>$imgpath ); $result=pdo_insert('lb_vote_info',$sign_data); if (!empty($result)) { $uid = pdo_insertid(); $msgdata['msg']='報名成功!,編號爲:'.$uid; } echo json_encode($msgdata); } } /*獲取access_token*/ function getaccesstoken(){ $appId='wxa3816b432f7291ba'; $appSecret='e469db86bec9661650362dc2f9df8956'; $ur="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}"; $chu= curl_init(); curl_setopt($chu, CURLOPT_URL, $ur); curl_setopt($chu, CURLOPT_SSL_VERIFYPEER, FALSE); curl_setopt($chu, CURLOPT_SSL_VERIFYHOST, FALSE); curl_setopt($chu, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($chu); curl_close($chu); $jsoninfo = json_decode($output, true); $access_token = $jsoninfo["access_token"]; /*獲取access_token*/ return $access_token; } /*下載圖片*/ function downlodimg($access_token,$serverId){ $targetName=dirname(dirname(dirname(__FILE__))).'/upload/images/'.rand(1,100).date('YmdHis').'.jpg'; $url="http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id={$serverId}"; $ch=curl_init($url); file_put_contents('urlres.log', $url); $fp=fopen($targetName, 'wb'); curl_setopt($ch, CURLOPT_FILE, $fp); curl_setopt($ch, CURLOPT_HEADER, 0); curl_exec($ch); curl_close($ch); fclose($fp); return $targetName; }
7.完整的頁面代碼json
<?php $url=dirname(dirname(dirname(dirname(dirname(dirname(dirname(__FILE__))))))); $url=$url.'/addons/lb_vote/jssdk.php'; include $url; $jsdk=new JSSDK('wxa3816b432f7291ba','e469db86bec9661650362dc2f9df8956'); $signPackage = $jsdk->GetSignPackage(); ?> <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0, user-scalable=0"> <title>報名</title> <link href="../addons/lb_vote/Public/css/mobile_signup.css" rel="stylesheet" type="text/css"> <link href="../addons/lb_vote/Public/css/bootstrap.min.css" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="http://cdn.bootcss.com/font-awesome/3.0.0/css/font-awesome.min.css" > <script type="text/javascript" src="../addons/lb_vote/Public/js/jquery.min.js"></script> <script type="text/javascript" src="../addons/lb_vote/Public/js/masonry.min.js"></script> <script type="text/javascript" src="../addons/lb_vote/Public/js/jquery.masonry.min.js"></script> <script type="text/javascript" src="../addons/lb_vote/Public/js/checkchjj.js"></script> <script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script> <style type="text/css"> /* .hint{ font-size: 10pt; color: red; display: none; } .dis{ font-size: 10pt; color: red; display: block; }*/ .img { filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale); } #errormsg{ position: absolute; display: none; text-align: center; margin-left: 100px; margin-top: 100px; background-color:#99CCFF; width: 200px; height: 35px; border:1px solid #99CCFF; border-radius:25px; font-size: 13pt; -moz-border-radius:25px; /* Old Firefox */ } </style> </head> <body> <header> <img class="header-img" src="http://bbs.sailingwed.com/source/plugin/hejin_toupiao/public/index/pic.png"/> <div class="stat"> <ul class="clearfix"> <li class="left"> <span class="top">報名人數</span> <span class="bottom">222</span> </li> <li> <span class="top">投票人數</span> <span class="bottom">333</span></li> <li> </ul> </div> <img class="header-img" src="../addons/lb_vote/Public/img/register.jpg"/> </header> <section class="content"> <div id="errormsg" > </div> <h2>報名處</h2> <form action="" method="post" > <input type="hidden" name="c" value="entry" /> <input type="hidden" value="signup" name="do"> <input type="hidden" value="sign" name="op"> <input type="hidden" value="lb_vote" name="m"> <input type="hidden" name="rid" value="{$id}" /> <div class="form-group"> <label for="exampleInputEmail1">姓名</label> <input type="uname" class="form-control" id="uname" name="uname" placeholder="姓名"> </div> <div class="form-group"> <label for="exampleInputPassword1">手機號</label> <input type="number" class="form-control" id="uphone" name="uphone" placeholder="手機號"> </div> <div class="form-group" > <label for="imgdis">圖片</label> <div class="imageitem"> <div class="upload_image"> <img name="imgdis" id="ImgPr" src=""/> </div> </div> <div> <div class="upload_btn" > <span class="icon-plus"></span> <input type="button" name="file" id="choose" /> </div> </div> </div> <div class="form-group" > <label for="exampleInputPassword1" >描述</label> <textarea class="form-control" name="discription" id="discrption"></textarea> </div> <button type="button" id="sbtn" onclick="subform();" class="form-control btn btn-danger " value="報名">報名</button> </form> </section> </body> <script type="text/javascript"> wx.config({ debug: false, // 開啓調試模式,調用的全部api的返回值會在客戶端alert出來,若要查看傳入的參數,能夠在pc端打開,參數信息會經過log打出,僅在pc端時纔會打印。 appId:'<?php echo $signPackage["appId"];?>', // 必填,公衆號的惟一標識 timestamp:<?php echo $signPackage["timestamp"];?>, // 必填,生成簽名的時間戳 nonceStr: '<?php echo $signPackage["nonceStr"];?>', // 必填,生成簽名的隨機串 signature:'<?php echo $signPackage["signature"];?>',// 必填,簽名,見附錄1 jsApiList: ['chooseImage','previewImage','uploadImage','downloadImage'] // 必填,須要使用的JS接口列表,全部JS接口列表見附錄2 }); var choose=document.getElementById('choose'); /*定義images用來保存選擇的本地圖片ID 和上傳的服務器圖片ID*/ var images={ localId:[], serverId:[], } wx.ready(function(){ var total=5;/*限制上傳的數量*/ var sum=0;/*每次上傳的數量*/ var upsum=0;/*已上傳的總數*/ choose.onclick=function(){ wx.chooseImage({ count:5,/*默認爲9*/ success:function(res){ images.localId=res.localIds;/*保存到images*/ sum=images.localId.length; if((upsum+sum)>total){ var last=total-upsum; alert('你還能夠選擇:'+last+'張'); return false; } /*圖片預覽*/ // wx.previewImage({ // current: res.localIds, // 當前顯示圖片的http連接 // urls: res.localIds // 須要預覽的圖片http連接列表 // }); /*相應位置預覽*/ var count=res.localIds.length+upsum; for(j=upsum;j<count;j++){ if(j==0){ $("#ImgPr").attr('src',res.localIds[0]); }else{ $new=$(".imageitem").last().clone(true); $new.find('img').attr('src',res.localIds[j-upsum]); $new.insertAfter($(".imageitem").last()); } } upsum=upsum+sum; /*上傳圖片到微信服務器*/ var i=0;len=images.localId.length; wxupload(); function wxupload(){ wx.uploadImage({ localId: images.localId[i], // 須要上傳的圖片的本地ID,由chooseImage接口得到 //isShowProgressTips: 1, // 默認爲1,顯示進度提示 success: function (res) { i++; //將上傳成功後的serverId保存到serverid images.serverId.push(res.serverId); if(i < len){ wxupload(); } } }); } /*上傳圖片*/ } } ); } }); /*驗證失敗時執行的函數*/ wx.error(function(res){ alert(res.errMsg); }); </script> <script type="text/javascript"> function subform(){ if(checkform()){ var str=''; var serverId=images.serverId; for(var i=0;i<serverId.length;i++){ str+='img='+serverId[i]; } $.ajax({ url:"{php echo $this->createMobileUrl('Signup',array('op'=>'sign'))}", type:'post', data:$("form").serialize()+"&imgserverid="+str, dataType:'json', success:function(data){ alert(data.msg); // if(data.success==1){ // // alert("報名成功"); // alert(data); // }else{ // alert(mydata.desc); // } } }); } } </script> </html>
以上就是PHP之微信JSSDK圖片上傳預覽下載到服務器的全文介紹,但願對您學習和使用php有所幫助.bootstrap