天天看點

微信js-sdk,選擇圖檔,上傳,下載下傳到本地,php服務端

翻閱了官方的文檔,找度娘問了前十頁,自己想,嘗試,終于有成果了。

官方的文檔,确實有點簡單了,對于初次接觸,是挺費勁的。

本功能由html發起,執行選擇圖檔,上傳圖檔操作,php接收html頁面post的來的參數,請求下載下傳圖檔,儲存到伺服器,順便把路徑儲存到資料庫。

CSS部分:

<style type="text/css">
.body{font-size: 14px;}
#imageContainer{}
#imageContainer ul,#imageContainer ul li{margin: 0;padding: 0;}
#imageContainer ul li{width:30%;padding-left:3px;float: left;list-style: none;min-height: 160px;overflow: hidden;}

.content{margin-bottom: 20px;border-left:solid 1px #d9d9d9;border-right: solid 1px #d9d9d9;  padding-top:5px;}
.content ul{min-height: 30px;height: auto;}
.content ul,.content ul li{margin:0;padding:0;}
.content ul li{float:left;width:75%;height: 30px;line-height:30px;list-style: none;font-size: 12px;
			border-bottom:solid 1px #d9d9d9;}
.content ul li input[type=text]{width:90%;margin-left: 5px;border:solid 1px #d9d9d9;}
.btn{background-color: #01b5e9;border:solid 1px #0094bf;border-radius: 4px;height: 25px;line-height: 25px; color:#fff;text-align: center;}

.titlecontainer{border-bottom: solid 1px #d9d9d9;;}
.title{float: left;width:100px;border-top: 2px solid #0094bf;height: 30px;line-height: 30px;text-align: center;
	border-left: solid 1px #d9d9d9;border-right:solid 1px #d9d9d9;color:#0094bf;font-weight: bold;}
.title_right{float: right;font-size: 14px;height: 30px;line-height: 30px;margin-right: 10px;}
.dia{font-size: 12px;}
/*width:100px;height: 30px;line-height:30px;border-radius: 5px;想弄個漂亮的提示框的
	text-align: center;background-color: #000;color:#fff;filter:alpha(opacity=50); -moz-opacity:0.5;opacity:0.5;
	position: fixed;z-index: 999;margin:0 auto;top:30%;left:37%;display: none;*/

</style>
           

HTML部分:

<div class="titlecontainer">
	<div class="title">添加商品</div>
	<div class="title_right">
		<a style="text-decoration: none;color:#000;font-size: 12px;font-weight: bold;" href="http://abc.com/index.php?g=User&m=Img&a=index&token={pigcms:$_SESSION['token']}" target="_blank" rel="external nofollow" >檢視所有商品</a>
	</div>
	<div style="clear: both;"></div>
</div>
<div class="content">
	<ul>
		<li style="width:25%;text-align: right;">商品标題:</li>
		<li><input type="text" id="txtname" maxlength="20" /></li>
		<li style="width:25%;text-align: right;">所屬類别:</li>
		<li><select id="seltype" style="margin-left: 5px;"><option value="">-請選擇-</option></select></li>
		<li style="width:25%;text-align: right;">商品詳情:</li>
		<li >
			<div style="margin-top:2px;margin-left: 6px;">
				<div class="btn"  id="selpic" style="width:70px;float: left;">選擇圖檔</div>
			</div>
		</li>
		
		<div style="clear: both;"></div>
	</ul>
	
</div>
<div class="btn"  id="uploadImage" style="width:70px;margin:0 auto;">儲存</div>
<div id="errormsg" class="dia"></div>
<div id="imageContainer" style="width:100%;margin-top:20px;">
	<ul></ul>
</div>
           

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);
  }
 }
           
微信js-sdk,選擇圖檔,上傳,下載下傳到本地,php服務端