微信js-sdk,选择图片,上传,下载到本地,php服务端

//前端js代码
<script> //客户端6.0.2 wx.config({ //debug:true, appId: "{pigcms:$signPackage.appId}", timestamp: {pigcms:$signPackage.timestamp}, nonceStr: ‘{pigcms:$signPackage.nonceStr}‘, signature: ‘{pigcms:$signPackage.signature}‘, url : ‘{pigcms:$signPackage.url}‘, jsApiList: [ ‘checkJsApi‘, ‘chooseImage‘, ‘previewImage‘, ‘uploadImage‘, ‘downloadImage‘ ] }); wx.ready(function() { // 1 判断当前版本是否支持指定 JS 接口,支持批量判断 wx.checkJsApi({ jsApiList: [ ‘chooseImage‘, ‘previewImage‘, ‘uploadImage‘, ‘downloadImage‘, ‘getNetworkType‘, ‘openLocation‘, ‘getLocation‘, ‘downloadVoice‘ ], success: function(res) { //alert(JSON.stringify(res)); } }); var images = { localId: [], serverId: [], downloadId: []//可以无视 }; var xmlHttpRequest; var accessToken=getCookie("accessToken"); //选择图片 document.getElementById("selpic").onclick = function() { $("#errormsg").append("开始选择图片<br />"); wx.chooseImage({ count: 9, // 默认9 sizeType: [‘compressed‘], // 可以指定是原图还是压缩图,默认二者都有‘original‘, success: function(res) { images.localId = res.localIds;// 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片 jQuery(function(){ var imglist=""; $.each( res.localIds, function(i, n){//这里是显示已选择的图片 imglist+=‘<li ><img src="‘+n+‘" style="width:95%;height:150px;" /></li>‘; //$("#errormsg").append("res.localIds:"+n+"<br />"); }); $("#imageContainer > ul").html(imglist); }); } }); } document.querySelector("#uploadImage").onclick = function () {//绑定onclick事件,如果没有这个按钮,要注释掉代码,不然点击无效 $("#errormsg").show(); $("#errormsg").append("<br />开始上传图片");//下文对此div赋值,只为了直观的看到动态效果 if (images.localId.length == 0) { alert(‘请先选择图片‘); return; } images.serverId = []; var localIds = images.localId; uploadimg(localIds); } var currentproindex=0; function getimgtoserver(serverIds){ //$("#errormsg").append("<br />serverIds length:"+serverIds.length+","); var classid=$("#seltype").val(); var classname=encodeURI($("#seltype option:selected").text());//传汉字需要转一下,php那边再翻转一下就好了 var serverId=serverIds.pop();//很微妙的方法,每次从数组取一个 var proname=encodeURI($("#txtname").val()); var newurl="http://ab.com/i_product.php?action=getwximg&proname="+proname+"&classid="+classid+"&classname="+classname+"&proindex="+currentproindex+"&uname={pigcms:$_SESSION[‘uname‘]}&uid={pigcms:$_SESSION[‘uid‘]}&token={pigcms:$_SESSION[‘token‘]}&wxurl=http://file.api.weixin.qq.com/cgi-bin/media/get&random="+Math.random()+"&accesstoken="+accessToken+"&mediaid="+serverId;//这里拼接地址,给服务器传参,下载图片需要在服务端处理,js请求存在跨域问题,并且,微信里,jq的初始xmlHttpRequest不能用,只能手写了,难道是我不会用jq? //$("#errormsg").append("<br />"+newurl); //$("#errormsg").append("<br />serverId:"+serverId) xmlHttpRequest.open("POST",newurl,true);//防止参数过长,还是用post方法吧 xmlHttpRequest.onreadystatechange=function(){ if (xmlHttpRequest.readyState==4){ if(xmlHttpRequest.status==200){ if(serverIds.length>0){ currentproindex+=1; getimgtoserver(serverIds);//递归调用,等本次成功,再开始第二个图片的上传操作 } else{ $("#errormsg").append("<br />上传成功"); } //$("#errormsg").append("<br />"+xmlHttpRequest.responseText); } else{ $("#errormsg").append(xmlHttpRequest.status); } } else if(xmlHttpRequest.readyState==1){ //$("#errormsg").append("<br />初始化成功"); } else if(xmlHttpRequest.readyState==2){ $("#errormsg").append("<br />正在发送数据"); } else if(xmlHttpRequest.readyState==3){ $("#errormsg").append("<br />正在等待服务器反馈"); } else{ $("#errormsg").append("发生错误了。");//+xmlHttpRequest.responseText); } } xmlHttpRequest.send(); } function uploadimg(localIds){ //$("#errormsg").append("<br />localIds length:"+localIds.length); var localId = localIds.pop(); wx.uploadImage({ localId: localId, // isShowProgressTips: 1, success: function (res) { images.serverId.push(res.serverId); //$("#errormsg").append("<br />"+res.serverId+","); if(localIds.length > 0){ uploadimg(localIds); } else{ if(window.XMLHttpRequest){ xmlHttpRequest=new XMLHttpRequest(); }else{ xmlHttpRequest=new ActiveXObject("MSXML2.XMLHTTP.3.0");//("Microsoft.XMLHTTP"); } $("#errormsg").append("<br />准备处理,请等待..."); var serverIds=images.serverId; getimgtoserver(serverIds); } }, fail: function (res) { alert("上传失败,请稍候重试"); } }); } }); wx.error(function(res) { alert(res.errMsg); }); //读取cookies function getCookie(name) { var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)"); if(arr=document.cookie.match(reg)) return (arr[2]); else return null; } function initsel(){ var url="http://abc.com/chat/i_product.php?action=getclothestype&token={pigcms:$_SESSION[‘token‘]}"; //alert(url); $.getJSON(url,function(data){ var str="<option value=‘‘>-请选择-</option>"; if(data.length>0){ for(i=0;i<data.length;i++){ str+="<option value=‘"+data[i].id+"‘>"+data[i].name+"</option>" } } $("#seltype").html(str); }); } $(function(){ initsel();//初始化下拉菜单 }); </script>
//php服务端代码
$act
= $_GET[‘action‘]; if ($act == ‘getwximg‘) { $wxurl=$_GET[‘wxurl‘]; $access_token=$_GET[‘accesstoken‘]; $media_id=$_GET[‘mediaid‘]; $newurl=$wxurl."?access_token=".$access_token."&media_id=".$media_id;//用php去请求获取图片的接口,js直接调用存在跨域问题 $token=$_GET[‘token‘]; $uid=$_GET[‘uid‘]; $uname=$_GET[‘uname‘]; $proindex=$_GET[‘proindex‘]; $classid=$_GET[‘classid‘]; $classname=urldecode($_GET[‘classname‘]);//取到的汉字,翻转一下 $proname=urldecode($_GET[‘proname‘]); $fileInfo = downloadWeixinFile($newurl);//通过接口,取结果 $filename = date("ymdhis",time()).".jpg";//图片名称 $time = time(); $newfolder="uploads/".date("y-m-d",$time)."/";//文件夹名称 saveWeixinFile($newfolder,$filename, $fileInfo["body"]);//把取到的base64代码,保存成图片 //echo $newurl; if($proindex==0){//因为图片是一次性上传的,这里判断一下,第一张作为产品的封面,剩下的作为产品的描述 $query = "INSERT INTO tp_img(uid,uname,token,createtime,uptatetime,classid,classname,title,pic) VALUE(‘".$uid."‘,‘".$uname."‘,‘".$token."‘,‘".$time."‘,‘".$time."‘,".$classid.",‘".$classname."‘,‘".$proname."‘,‘http://abc.com/chat/".$newfolder.$filename."‘)"; //$query = "INSERT INTO t_ChatMessage(UserCode,Contents,ToUser,IsRead) VALUE(‘$sendid‘, ‘$msg‘,‘$toid‘,‘0‘)"; $result = mysql_query($query) or die("{\"error\":true,\"errorMsg\":\"Error in query: $query. " . mysql_error()."\"}"); } else{ $query ="select * from tp_img where token=‘".$token."‘ order by uptatetime desc limit 1"; $result = mysql_query($query) or die("{\"error\":true,\"errorMsg\":\"Error in query: $query. " . mysql_error()."\"}"); $items = array(); while($row = mysql_fetch_array($result)){ array_push($items, ($row)); $query_update="update tp_img set info=CONCAT(info,‘‘,‘<div style=\"margin-top:3px;\"><img src=\"http://abc.com/chat/".$newfolder.$filename."\" /></div>‘) where id=$row[id]";//在产品描述的字段上追加内容 mysql_query($query_update); } } //echo "{\"error\":\""+$rtmsg+"\"}"; }
function downloadWeixinFile($url)  
{  
    $ch = curl_init($url);  
    curl_setopt($ch, CURLOPT_HEADER, 0);      
    curl_setopt($ch, CURLOPT_NOBODY, 0);    //只取body头  
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);  
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);  
    $package = curl_exec($ch);  
    $httpinfo = curl_getinfo($ch);  
    curl_close($ch);  
    $imageAll = array_merge(array(‘header‘ => $httpinfo), array(‘body‘ => $package));   
    return $imageAll;  
}  
   
function saveWeixinFile($newfolder,$filename, $filecontent)  
{     
    createFolder($newfolder);  
    $local_file = fopen($newfolder."/".$filename, ‘w‘);  
    if (false !== $local_file){  
          
        if (false !== fwrite($local_file, $filecontent)) {  
          
            fclose($local_file);  
         
        }  
    }  
}  
 function createFolder($path)  
 {  
  if (!file_exists($path))  
  {  
   createFolder(dirname($path));  
   mkdir($path, 0777);  
  }  
 }  

 

//第二种方法

$accessToken = ‘公众号 AccessToken‘;
$media_id = ‘wx.uploadImage 返回的 serverId‘;

// 要存在你服务器哪个位置?
$targetName = ‘./tmp/‘.date(‘YmdHis).‘.jpg‘;

$ch = curl_init("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$accessToken}&media_id={$serverId}");
$fp = fopen(FCPATH.$targetName, ‘wb‘);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_exec($ch);
curl_close($ch);
fclose($fp);

 

微信js-sdk,选择图片,上传,下载到本地,php服务端

上一篇:zabbix3.0 安装方法,一键实现短信、电话、微信、APP 告警


下一篇:两步快速获取小程序源码