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

本文介绍了如何使用微信JS-SDK实现图片选择、上传功能,并详细阐述了PHP服务端如何接收图片,进行下载保存到服务器及路径存入数据库的过程。在实践中,开发者可能会发现官方文档提供的信息不足,需要通过自我探索和实践来完善解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

翻阅了官方的文档,找度娘问了前十页,自己想,尝试,终于有成果了。

官方的文档,确实有点简单了,对于初次接触,是挺费劲的。

本功能由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']}">查看所有商品</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);
  }
 }



评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值