ThinkPHP微信实例——JSSDK图像接口多张图片上传下载并将图片流写入本地

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>发布图片</title>
<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="format-detection" content="telephone=no">
<link rel="stylesheet" type="text/css" href="/Public/Weixin/css/common.css">
</head>
<body>
<p>最多可添加9张作品</p>
<input type="file" id="uploadphoto" name="uploadfile" value="请点击上传图片"   style="display:none;" />  
<div class="imglist"></div>
<input type="hidden" id="img_str" name="img_str"> 
<a id="upload_button" href="javascript:void(0);" class="uploadImage uploadbtn"><img src="/Public/Weixin/images/upload-add.png" alt=""></a> 
<div class="sb">发布</div>
<script type="text/javascript" src="/Public/Weixin/js/jquery.min.js"></script>
<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script>  
wx.config({
debug: false,
appId: '{$signPackage["appid"]}',
timestamp: {$signPackage["timestamp"]},
nonceStr: '{$signPackage["noncestr"]}',
signature: '{$signPackage["signature"]}',
jsApiList: [
// 所有要调用的 API 都要加到这个列表中
'chooseImage','previewImage','uploadImage','downloadImage'
]
});
wx.ready(function () {
// 5.3 上传图片
$('.uploadImage').on('click', function () {
	wx.chooseImage({
		success: function (res) {
			var localIds = res.localIds;
			syncUpload(localIds);
		}
	});
});
var syncUpload = function(localIds){
	var localId = localIds.pop();
	wx.uploadImage({
	localId: localId,
	isShowProgressTips: 1,
	success: function (res) {
	    var serverId = res.serverId; // 返回图片的服务器端ID
            var str = $('#img_str').val()+serverId+',';
            $('.imglist').append("<img src='"+localId+"' />");
            $('#img_str').val(str);
	    //其他对serverId做处理的代码
	    if(localIds.length > 0){
		syncUpload(localIds);
	    }
            if($('.imglist img').size() >= 9) {
                $("#upload_button").hide();
            }
	},
	fail: function (res) { alert(JSON.stringify(res)); }
    });
};
});
</script>

<script>

  $(".sb").click(function(){
      var imglist = $(".imglist").html();
     
      if(imglist == "" || imglist == null) {
         alert("请添加图片");
           return false;
      } else {
          if($(".imglist").find('img').size() >9) {
              alert("图片只允许上传9张!");
              return false;
          }
	  var img_str = $('#img_str').val();
      }

      $.post("{:U('Test/wxupload')}", {img_str:img_str},function(data){
          window.location.href = "__URL__/test";
      });
  });

</script>
</body>
</html>


后台处理 testController.php

    public function test() {
	$signPackage = $this->getSignPackage();
	$this->assign('signPackage', $signPackage);
	$this->display('test');
    }


    public function wxupload() {
	header('Content-type:application/json;chartset=utf-8');
	$img_str = I('post.img_str', '', 'string');
      	$uploadROOT 	= realpath(THINK_PATH.'../Public/');//定义保存路径     
	$uploadPath 	= $uploadROOT."/Upload/".date('Y-m-d')."/";//为方便管理图片 保存图片时 已时间作一层目录作区分
	if(!file_exists($uploadPath)) mkdir($uploadPath,  0775);
				
	$savepath = '/Public/Upload/' . date('Y-m-d').'/'; 
	$img_str = rtrim($img_str, ',');

	$img_arr = explode(',', $img_str);
	$str = ''; //sql语句字符串
	$imgs = array();

	foreach($img_arr as $v) {
		$imgs[] = $this->doWechatPic($v);
	}
		
	$str = ''; //sql语句字符串
	foreach($imgs as $v) {
		$str .= "(NULL," . $this->_user_info_id . "," . $publish_id . ",'" . $v . "')" . ",";
	}
	$sql = "INSERT INTO img(`id`,`userid`,`publish_id`,`img_url`) values" . rtrim($str, ',');
	$res = M()->query($sql);			
	
	if($res) {
		 $data = array('errcode' => 0, 'msg' => '成功!');
	} else {
		 $data = array('errcode' => 1, 'msg' => '失败!');
	}
	exit( JSON($data));
    }

	/* 
	 * 从微信服务器获取图片流 
	 */  
	public function doWechatPic($serverId){//media_id=jlJs_iQIOA-TKLuhk4nCdPEdXnJ6paIeToO8vr-WUGvz05-6i5n498EzI232xSxn   
	       $media_id = $serverId;//提交过来的serverId即$media_id     
	       $access_token 	= $this->_get_wx_access_token_address( false );//获取access_token值
	      
	        $pic_url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token={$access_token}&media_id={$media_id}";  
	        $filebody = file_get_contents($pic_url);//通过接口获取图片流  
	        
	        $filename = uniqid().'.jpg';            //定义图片名字及格式  
	        return $this->saveFile($filename, $filebody);  
	}  
	  
	/* 
	 * 定义文件路径,写入图片流 
	 */  
	public function saveFile($filename, $filecontent){  

	    $uploadROOT 	= realpath(THINK_PATH.'../Public/');//定义保存路径     
		$uploadPath 	= $uploadROOT."/Upload/".date('Y-m-d')."/";//为方便管理图片 保存图片时 已时间作一层目录作区分
		if(!file_exists($uploadPath)) mkdir($uploadPath,  0775);
	    $upload_dir = '/Public/Upload/' . date('Y-m-d'); //保存路径,以时间作目录分层  
	    $savepath = '.'.$upload_dir.'/'.$filename;       
	    
	    if(file_put_contents($savepath, $filecontent)){//写入图片流生成图片  
	        return $upload_dir."/".$filename;//返回图片路径  
	    }else{  
	        exit(JSON('save failed'));  
	    }  
	      
	} 

需要注意的是 access_token,signPackage参数不能错误


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值