1. 程式人生 > >基於ThinkPHP頭像上傳例項

基於ThinkPHP頭像上傳例項

參考: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):

<?php
namespace 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):
<?php
return 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(), // 上傳驅動配置
    ),
);
?>