此次学习的是上传图片生成一个链接,可以访问图片。
首先,显示新增素材界面。
public function addmeterial($type=''){
if(empty($type)){
$type = 'image';
}
$this->assign('type',$type);
$this->assign('action',$type.'_submit');
$this->display();
}
图片提交
首先,实例化上传类,设置附件上传大小,类型及上传根(子)目录,然后调用upload方法上传图片。
//提交图片
public function upload(){
$upload = new \Think\Upload();// 实例化上传类
$upload->maxSize = 3145728 ;// 设置附件上传大小
$upload->exts = array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
$upload->rootPath = './Uploads/'; // 设置附件上传根目录
$upload->savePath = ''; // 设置附件上传(子)目录
// 上传文件
$info = $upload->uploadOne($_FILES['file']);
if(!$info) {// 上传错误提示错误信息
$this->ajaxReturn(array('code'=>1,'msg'=>$upload->getError()));
// $this->error($upload->getError());
}else{// 上传成功
$file = '/Uploads/'.$info['savepath'].$info['savename'];
$this->ajaxReturn(array('code'=>0,'msg'=>'上传成功','url'=>$file));
}
}
图片上传到公众号服务器中
首先获取图片的路径,获取access_token,引入lanewechat文件,最后选择提交为临时或永久素材
//图片上传公众号服务器
public function image_submit(){
$url = I('post.url');//图片在服务器上的路径
//相对路径->绝对路径
$file = realpath('.'. $url);
// echo $file;
// exit;
$staus_type = I('post.staus_type');//临时,永久
$accessToken = getAccess_token();
include APP_PATH . 'LaneWeChat/lanewechat.php';
if($staus_type == 0){
//临时素材
$url="https://api.weixin.qq.com/cgi-bin/media/upload?access_token=$accessToken&type=image";
}else{
//永久素材
$url="https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=$accessToken&type=image";
}
$data['media'] = '@' . $file;
$ret = Curl::callWebServer($url,$data,'post',true,false);
$this->ajaxReturn($ret);
}