PHP之微信JSSDK图片上传预览下载到服务器
2016-11-03 00:00
796 查看
1.投票报名
主要实现报名功能
(1)form表单布局
2.js检验输入的正确性
3.微信JSSDK图片上传功能
3.1 jssdk.php jsapi_ticket.php access_token.php 放在项目文件下
3.2获取wx.config所需要的信息
页面中添加如下代码
3.3实现图片预览和上传到微信服务器功能
4.图片上传到微信服务器以后 提交报名 使用AJAX将表单提交到php文件
5.php端从微信服务器下载图片
5.1获取access_token
5.2从微信服务器下载图片
6.完整的PHP报名代码
7.完整的页面代码
以上就是PHP之微信JSSDK图片上传预览下载到服务器的全文介绍,希望对您学习和使用php有所帮助.
主要实现报名功能
(1)form表单布局
<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检验输入的正确性
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所需要的信息
页面中添加如下代码
<?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实现图片预览和上传到微信服务器功能
<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文件
<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_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; }
5.2从微信服务器下载图片
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.完整的页面代码
<?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有所帮助.
相关文章推荐
- 微信jssdk多图片上传下载到服务器
- 微信小程序图片选择、上传到服务器、预览(PHP)实现实例
- 微信公众号开发《四》使用微信JS-SDK实现手机图片上传,支持压缩、预览。并下载图片到自身服务器
- 微信小程序图片选择、上传到服务器、预览(PHP)实现实例
- PHP仿微信多图片预览上传
- PHP仿微信多图片预览上传功能
- PHP实现微信图片上传到服务器的方法示例
- 微信jssdk上传图片无法预览wxLocalResource文件
- PHP仿微信多图片预览上传实例代码
- 把图片上传到微信服务器,php开发公众号编辑器
- php向服务器上传文件以及图片预览
- PHP仿微信多图片预览上传
- 微信js-sdk,选择图片,上传,下载到本地,php服务端
- 微信js上传的图片只能保存3天 下载到自己的服务器
- PHP调用微信JSSDK接口 选择相册及拍照、图片上传
- 微信jsapi开发教程之微信jsapi选择图片,上传图片,预览和下载图片(第六课)
- 微信jsapi开发教程之微信jsapi选择图片,上传图片,预览和下载图片(第六课)
- PHP 使用 微信JSSDK 拍照选择图片接口 利用localid预览时 安卓手机正常显示 iOS手机不显示
- thinkphp微信开发之jssdk图片上传并下载到本地服务器
- 微信小程序上传图片到php服务器