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






发布图片







最多可添加9张作品

发布


后台处理 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参数不能错误


你可能感兴趣的:(ThinkPHP微信实例——JSSDK图像接口多张图片上传下载并将图片流写入本地)