基于ThinkPHP头像上传实例

来源:互联网 发布:centos安装php两个环境 编辑:程序博客网 时间:2024/05/22 02:04

参考:http://www.thinkphp.cn/topic/29123.html

如果上面的链接失效的话就在这下载:https://pan.baidu.com/s/1nvgOid7    

提取码 :j8p6

将参考网址中的文件复制到自己的项目中,主要需要第三方扩展文件中的(Vendor/ThinkImage),Public中的相关css和js,因为项目需要,将人家的修改了一点点,上传后的图片直接存储裁剪后的,其余裁剪的图片都不需要,(Home/Common)中的function.php里面的命名函数删除了,因为我这里采取的时间戳命名,增加了“重新上传”时,删除磁盘中的图片(IndexController.class.php):

<?phpnamespace Home\Controller;use Think\Controller;use Vendor\ThinkImage\ThinkImage;class IndexController extends Controller {public function _iniaitlize(){header("Content-type:text/html;charset=utf-8");}//初始化页面        public function index(){        $this->display();        }//上传头像public function uploadImg(){$upload = new \Think\Upload(C('UPLOAD_CONFIG'));// 实例化上传类 , C('UPLOAD_CONFIG')配置见下面//头像目录地址$path = './Public/upload/headimg/'.date('Ymd').'/';if(!$upload->upload()) {// 上传错误提示错误信息$this->ajaxReturn(array('status'=>0,'info'=>$upload->getErrorMsg()));}else{// 上传成功 获取上传文件信息$temp_size = getimagesize($path.time().'.jpg');if($temp_size[0] < 100 || $temp_size[1] < 100){//判断宽和高是否符合头像要求$this->ajaxReturn(array('status'=>0,'info'=>'图片宽或高不得小于100px!'));}$this->ajaxReturn(array('status'=>1,'path'=>$path.time().'.jpg','filename'=>date('Ymd').'/'.time().'.jpg'));}}//裁剪并保存用户头像public function cropImg(){//图片裁剪数据$params = I('post.');//裁剪参数if(!isset($params) && empty($params)){$this->error('参数错误!');}//头像目录地址$path = './Public/upload/headimg/';//要保存的图片$real_path = $path.I('filename');//临时图片地址$pic_path = $path.I('filename');//实例化裁剪类$Think_img = new ThinkImage(THINKIMAGE_GD);//裁剪原图得到选中区域$Think_img->open($pic_path)->crop($params['w'],$params['h'],$params['x'],$params['y'])->save($real_path);//生成缩略图//$Think_img->open($real_path)->thumb(100,100, 1)->save($path.I('filename').'_100.jpg');//$Think_img->open($real_path)->thumb(60,60, 1)->save($path.I('filename').'_60.jpg');//$Think_img->open($real_path)->thumb(30,30, 1)->save($path.I('filename').'_30.jpg');$this->success('上传头像成功');}//当用户点击重新上传后,删除本地磁盘中的文件public function deleteImg(){        $result = unlink(realpath('./Public/upload/headimg/'.I("pathname")));    if($result){       $data['status']=1;    }else{       $data['status']=0;    }    $this->ajaxReturn($data);    }}?>
前台模块增加了隐藏域,以便将图片值带走(index.html):
<!DOCTYPE html><html><head>    <meta charset="utf-8"><title>头像上传</title><load href="__PUBLIC__/css/jquery.Jcrop.min.css" /><load href="__PUBLIC__/css/bootstrap.css" /><load href="__PUBLIC__/js/uploadify-v3.1/uploadify.css" /><load href="__PUBLIC__/js/jquery-3.1.1.min.js" /><load href="__PUBLIC__/js/bootstrap.min.js" /><load href="__PUBLIC__/js/uploadify-v3.1/jquery.uploadify-3.1.min.js" /><load href="__PUBLIC__/js/jquery.Jcrop.min.js" /><load href="__PUBLIC__/js/ThinkBox/jquery.ThinkBox.js" /><load href="__PUBLIC__/js/ThinkBox/css/ThinkBox.css" /><style type="text/css">.main{ margin: 0 auto; padding: 15px; width: 450px; height: 250px; font-family: "microsoft yahei";background-color: #F5F5F5; }.upload-area { position: relative; float: left;margin-right: 30px;width: 200px; height: 200px;background-color: #F5F5F5; border: 2px solid #E1E1E1; }.upload-area .file-tips { position: absolute; top: 90px; left: 0; padding: 0 15px; width: 170px;    line-height: 1.4; font-size: 12px; color: #A8A8A3; text-align: center; }.userup-icon { display: inline-block; margin-right: 3px; width: 16px; height: 16px; vertical-align: -2px; background: url("__PUBLIC__/images/userup_icon.png") no-repeat;}.uploadify-button { line-height: 120px!important; text-align: center; }.preview-area {float: left; }.tcrop { clear: right; font-size: 14px; font-weight: bold; }.update-pic .crop { background: url("__PUBLIC__/images/mystery.png") no-repeat scroll center center #EEEEEE; float: left; margin-bottom: 20px; margin-top: 10px; overflow: hidden; }.crop100 { height: 100px; width: 100px; }.crop60 { height: 60px; margin-left: 20px; width: 60px;}.preview { position: absolute; top: 0; left: 0;z-index: 11; width: 200px; height: 200px; overflow: hidden;background:#fff; display: none;}</style></head><body><div class="main"><!-- 修改头像 --><form action="{:U('Index/cropImg')}" method="post" id="pic" class="update-pic cf">        <!--刚刚上传的图片,因为是时间戳形式,所以需要将值带走--><input type="hidden" name="filename" id="filename"><div class="upload-area">    <input type="file" id="user-pic"><div class="file-tips"></div><div class="preview hidden" id="preview-hidden"></div></div><div class="preview-area"><input type="hidden" id="x" name="x" /><input type="hidden" id="y" name="y" /><input type="hidden" id="w" name="w" /><input type="hidden" id="h" name="h" /><input type="hidden" id='img_src' name='src'/><div class="tcrop">头像预览</div><div class="crop crop100"><img id="crop-preview-100" src="" alt=""></div><div class="crop crop60"><img id="crop-preview-60" src="" alt=""></div></div><br/><button type="submit" class="btn btn-primary save-pic">保存头像</button><a class="btn btn-primary reupload-img" style="text-decoration:none;">重新上传</a></form></div><!-- /修改头像 --><script type="text/javascript">$(function(){//上传头像(uploadify插件)$("#user-pic").uploadify({'queueSizeLimit' : 1,'removeTimeout' : 0.5,'preventCaching' : true,'multi'    : false,'swf' : '__PUBLIC__/js/uploadify-v3.1/uploadify.swf','uploader' : '{:U("Index/uploadImg")}','buttonText' : '<i class="userup-icon"></i>上传头像','width' : '200','height' : '200','fileTypeExts': '*.jpg; *.png; *.gif;','onUploadSuccess' : function(file, data, response){//调试语句console.log(data);var data = $.parseJSON(data);$("#filename").val(data['filename']);  //将刚刚上传的图片名称读取出来if(data['status'] == 0){$.ThinkBox.error(data['info'],{'delayClose':3000});return;}var preview = $('.upload-area').children('#preview-hidden');preview.show().removeClass('hidden');//两个预览窗口赋值$('.crop').children('img').attr('src',data['path']+'?random='+Math.random());//隐藏表单赋值$('#img_src').val(data['path']);//绑定需要裁剪的图片var img = $('<img />');preview.append(img);preview.children('img').attr('src',data['path']+'?random='+Math.random());var crop_img = preview.children('img');crop_img.attr('id',"cropbox").show();var img = new Image();img.src = data['path']+'?random='+Math.random();//根据图片大小在画布里居中img.onload = function(){var img_height = 0;var img_width = 0;var real_height = img.height;var real_width = img.width;if(real_height > real_width && real_height > 200){var persent = real_height / 200;real_height = 200;real_width = real_width / persent;}else if(real_width > real_height && real_width > 200){var persent = real_width / 200;real_width = 200;real_height = real_height / persent;}if(real_height < 200){img_height = (200 - real_height)/2;}if(real_width < 200){img_width = (200 - real_width)/2;}preview.css({width:(200-img_width)+'px',height:(200-img_height)+'px'});preview.css({paddingTop:img_height+'px',paddingLeft:img_width+'px'});}//裁剪插件$('#cropbox').Jcrop({            bgColor:'#333',   //选区背景色            bgFade:true,      //选区背景渐显            fadeTime:1000,    //背景渐显时间            allowSelect:false, //是否可以选区,            allowResize:true, //是否可以调整选区大小            aspectRatio: 1,     //约束比例            minSize : [100,100],//可选最小大小            boxWidth : 200,//画布宽度            boxHeight : 200,//画布高度            onChange: showPreview,//改变时重置预览图            onSelect: showPreview,//选择时重置预览图            setSelect:[ 0, 0, 100, 100],//初始化时位置            onSelect: function (c){//选择时动态赋值,该值是最终传给程序的参数!            $('#x').val(c.x);//需裁剪的左上角X轴坐标            $('#y').val(c.y);//需裁剪的左上角Y轴坐标            $('#w').val(c.w);//需裁剪的宽度            $('#h').val(c.h);//需裁剪的高度          }        });//提交裁剪好的图片$('.save-pic').click(function(){if($('#preview-hidden').html() == ''){$.ThinkBox.error('请先上传图片!');}else{//由于GD库裁剪gif图片很慢,所以长时间显示弹出框$.ThinkBox.success('图片处理中,请稍候……',{'delayClose':30000});$('#pic').submit();}});     }});//重新上传,清空裁剪参数$('.reupload-img').click(function(){$.ajax({type:"post",data:{pathname:$("#filename").val()},url:"{:U('Index/deleteImg')}",dataType:"json",success:function(data){if(data.status==1){$(".preview-area").load(location.href+" .preview-area");}}});$('#preview-hidden').find('*').remove();$('#preview-hidden').hide().addClass('hidden').css({'padding-top':0,'padding-left':0});});//预览图function showPreview(coords){var img_width = $('#cropbox').width();var img_height = $('#cropbox').height();  //根据包裹的容器宽高,设置被除数  var rx = 100 / coords.w;  var ry = 100 / coords.h;  $('#crop-preview-100').css({    width: Math.round(rx * img_width) + 'px',    height: Math.round(ry * img_height) + 'px',    marginLeft: '-' + Math.round(rx * coords.x) + 'px',    marginTop: '-' + Math.round(ry * coords.y) + 'px'  });  rx = 60 / coords.w;  ry = 60 / coords.h;  $('#crop-preview-60').css({    width: Math.round(rx * img_width) + 'px',    height: Math.round(ry * img_height) + 'px',    marginLeft: '-' + Math.round(rx * coords.x) + 'px',    marginTop: '-' + Math.round(ry * coords.y) + 'px'  });}})</script></body></html>
图片上传的公共配置(Home/Conf/config.php):

<?phpreturn array(//图片上传配置'UPLOAD_CONFIG' => array(        'mimes'         =>  array(), //允许上传的文件MiMe类型        'maxSize'       =>  0, //上传的文件大小限制 (0-不做限制)        'exts'          =>  array('jpg', 'gif', 'png', 'jpeg'), //允许上传的文件后缀        'autoSub'       =>  true, //自动子目录保存文件           'subName'       =>  array('date','Ymd'), //子目录创建方式,[0]-函数名,[1]-参数,多个参数使用数组             'rootPath'      =>  './Public/upload/headimg/', //保存根路径                'savePath'      =>  '', //保存路径        'saveName'      =>  'time', //上传文件命名规则,[0]-函数名,[1]-参数,多个参数使用数组        'saveExt'       =>  'jpg', //文件保存后缀,空则使用原后缀        'replace'       =>  true, //存在同名是否覆盖        'hash'          =>  true, //是否生成hash编码        //'callback'      =>  false, //检测文件是否存在回调,如果存在返回文件信息数组        //'driver'        =>  'Local', // 文件上传驱动        //'driverConfig'  =>  array(), // 上传驱动配置    ),);?>