准备材料
- THINKPHP3.2.3
- jQuery表单插件
- cropper 裁剪插件
思路: 利用THINKPHP上传文件类与图片裁剪类,前台想办法组合参数给后台 那怎么样可以异步提交文件呢 关键就是 jquery表单插件了
后台准备
thinkphp 上传类 http://www.kancloud.cn/manual/thinkphp/1876
thinkphp 裁剪类 http://www.kancloud.cn/manual/thinkphp/1878
前台准备
jQuery表单插件 http://malsup.com/jquery/form/#code-samples 中文文档 http://www.cnblogs.com/linzheng/archive/2010/11/17/1880288.html
裁剪插件 http://www.jqcool.net/image-cropper.html https://github.com/fengyuanchen/cropper
即时预览图片 (不会上传文件)
/**
* 从 file 域获取 本地图片 url
*/
function getFileUrl(sourceId) {
var url;
if (navigator.userAgent.indexOf("MSIE")>=1) { // IE
url = document.getElementById(sourceId).value;
} else if(navigator.userAgent.indexOf("Firefox")>0) { // Firefox
url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
} else if(navigator.userAgent.indexOf("Chrome")>0) { // Chrome
url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
}
return url;
}
/**
* 将本地图片 显示到浏览器上
*/
function preImg(sourceId, targetId) {
var url = getFileUrl(sourceId);
var imgPre = document.getElementById(targetId);
imgPre.src = url;
}
//触发事件调用
preImg(this.id,'imgPre');
我的实现代码
前端
<form id="avatar_form" action="{:U('Picture/ajaxAvatar')}" method="post" enctype="multipart/form-data">
<div class="txsc">
<input type="hidden" class="avatar-data" name="avatar_data"><!-- 头像裁剪数据 -->
<div class="close"><img src="__IMG__/icon12.png" width="15" height="16" /></div>
<div class="tx_top">
<p>
<span class="l">上传新头像</span>
<span class="file">选择文件<input id="imgOne" type="file" name="avatar_file"></span>
<span class="l">未选择文件</span>
</p>
<p class="font12 color4">支持格式:jpg、jpeg、png、gif格式,大小不超过5M</p>
</div>
<div class="tx_img">
<P>
<div class="container avatar_img">
<img id="imgPre" src="__IMG__/img12.jpg" width="291" />
</div>
</P>
<P class="fangda"><span id="enlarge"><img src="__IMG__/icon19.png" width="18" height="18" /></span><span id="shrink" style="border-left:#c1c1c1 solid 1px;"><img src="__IMG__/icon18.png" width="18" height="18" /></span></P>
</div>
<div class="tx_an"><span id="avatar_sumbit" class="button l">确定</span><span id="resetUplode" class="button1 r">重新上传</span></div>
<div class="tx_ts"><p>温馨提示:</p><p>禁止上传违反中华人民共和国相关法律的照片,若上传,相关
法律后果有个人承担</p></div>
</div>
</form>
<script>
//头像上传裁剪 start
$(function(){
//打开或关闭弹出层
$(document).ready(function() {
$('.toux').click(function(){
$('.txsc').fadeIn(300);
})
$('.txsc .close').click(function(){
$('.txsc'). fadeOut(300);
})
});
/**
* 从 file 域获取 本地图片 url
*/
function getFileUrl(sourceId) {
var url;
if (navigator.userAgent.indexOf("MSIE")>=1) { // IE
url = document.getElementById(sourceId).value;
} else if(navigator.userAgent.indexOf("Firefox")>0) { // Firefox
url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
} else if(navigator.userAgent.indexOf("Chrome")>0) { // Chrome
url = window.URL.createObjectURL(document.getElementById(sourceId).files.item(0));
}
return url;
}
/**
* 将本地图片 显示到浏览器上
*/
function preImg(sourceId, targetId) {
var url = getFileUrl(sourceId);
var imgPre = document.getElementById(targetId);
imgPre.src = url;
}
//先清除原来的图片
$("#imgOne").click(function(){
$('.avatar_img').html('<img id="imgPre" src="__IMG__/img12.jpg" width="291" />');
})
//点击重新上传相当于点击了上传文件
$("#resetUplode").click(function(){
$("#imgOne").click();
})
$("#imgOne").live('change',function(){
preImg(this.id,'imgPre');
//图片裁剪初始化
$('.container > img').cropper({
aspectRatio: 16 / 9,
rotateControls:true,
zoomable: true,
crop: function(data) {
//$('.avatar-data').
var x = data.x;
var y = data.y;
var width = data.width;
var height = data.height;
var avatarData = '{"x":'+x+',"y":'+y+',"height":'+height+',"width":'+width+',"rotate":0}';
$('.avatar-data').val(avatarData);
}
});
});
//放大
$("#enlarge").click(function(){
$('.container > img').cropper('zoom', +0.1);
})
//缩小
$("#shrink").click(function(){
$('.container > img').cropper('zoom', -0.1);
})
/* 异步上传图片 */
$("#avatar_sumbit").click(function(){
$('#avatar_form').ajaxSubmit(function(data){
//console.log(data);
//替换当前图片的路径
$(".toux").attr('src',data.crop_path);
//接收图片ID后,放到当前页面中
$("input[name='head_img']").val(data.pic_id);
//关闭当前弹出层
$('.txsc'). fadeOut(300);
});
return false;
});
});
//头像上传裁剪 end
</script>
PHP端
控制器中的方法
public function ajaxAvatar(){
$avatarArr = json_decode(I('post.avatar_data'),1);
$picModel = D('picture');
$info = $picModel->ajaxUpload($_FILES,$avatarArr);
$this->ajaxReturn($info);
}
图片model层代码
/**
* 图片上传
* @param array $files 要上传的图片列表(通常是$_FILES数组)
* @param array $setting 图片上传配置
* @param string $driver 图片驱动名称
* @param array $config 图片驱动配置
* @return array 图片上传成功后的信息
*/
public function upload($files, $setting, $driver = 'Local', $config = null){
/* 上传文件 */
$Upload = new \Think\Upload($setting, $driver, $config);
$info = $Upload->upload($files);
/* 设置文件保存位置 */
$this->_auto[] = array('location', 'Ftp' === $driver ? 1 : 0, self::MODEL_INSERT);
if($info){ //文件上传成功,记录文件信息
foreach ($info as $key => &$value) {
/* 已经存在文件记录 */
if(isset($value['id']) && is_numeric($value['id'])){
$value['path'] = substr($setting['rootPath'], 1).$value['savepath'].$value['savename']; //在模板里的url路径
continue;
}
$value['path'] = '.'.substr($setting['rootPath'], 1).$value['savepath'].$value['savename']; //在模板里的url路径
/* 记录文件信息 */
if($this->create($value) && ($id = $this->add())){
$value['id'] = $id;
} else {
//TODO: 文件上传成功,但是记录文件信息失败,需记录日志
unset($info[$key]);
}
}
return $info; //文件上传成功
} else {
$this->error = $Upload->getError();
return false;
}
}
/*更新或添加*/
public function update($data)
{
$data = $this->create($data);
if(!$data){ return false;}
return empty($data['id']) ? $this->add() : $this->save();
}
/**
*异步上传并裁剪图片
* @param $file $_FILES 文件信息
* @param $pic 要裁剪信息
* @param $pre 裁剪后图片前缀
* @return array 图片裁剪之后的地址 原图片地址 图片ID
*/
public function ajaxUpload($file,$picArr,$pre='crop'){
$config = array(
'maxSize' => 3145728,
'rootPath' => './Uploads/Picture/',
'savePath' => '',
'saveName' => array('uniqid',''),
'exts' => array('jpg', 'gif', 'png', 'jpeg'),
'autoSub' => true,
'subName' => array('date','Y-m-d'),
);
//可以直接调用系统的上传类
$info = $this->upload($file,$config);
//截图略缩图
$image = new \Think\Image();
$image->open($info['avatar_file']['path']);
$crop_path = './Uploads/Picture/'.$info['avatar_file']['savepath'].$pre.'_'.$info['avatar_file']['savename'];
$image->crop($picArr['width'], $picArr['height'],$picArr['x'],$picArr['y'])->save($crop_path);
//原图片路径
$info['org_path'] = $info['avatar_file']['path'];
//裁剪后图片路径
$info['crop_path'] = $crop_path;
//图片ID
$info['pic_id'] = $info['avatar_file']['id'];
return $info;
}