php+js iframe实现上传头像界面无跳转


Posted in PHP onApril 29, 2014

上传头像,界面无跳转的方式很多,我用的是加个iframe那种。下面直接上代码。

html:

//route 为后端接口 
//upload/avatar 为上传的头像的保存地址 
//imgurl=/upload/avatar/<?=$uid?> 这里最后的<?=$uid?>是为了后面用js实现即时显示最新的更换后的头像用的,参照下面的js部分的代码 
//头像保存名称为uid.type,如1.jpg,2.png等 
//$user['avatar'] 用户如果上传过头像,该用户数据库中的avatar字段将赋予时间戳,否则为空 
<form target="iframe" enctype="multipart/form-data" action="route?imgurl=/upload/avatar/<?=$uid?>" method="post" id="upload_form"> 
<img class="thumb" src="<?php if($user['avatar']) echo $my_img; else echo '/view/img/100.png'; ?>" style="width:100px; height:100px;" /> 
<input type="file" name="file" size="28" /> 
<input type="submit" name="submit_file" value="确定" style="display: none;"/> 
</form> 
<iframe id="iframe" name="iframe" style="display: none;"></iframe>

php:
$token = param('token'); 
$user = user_from_token($token); 
!$user AND exit("<p class='iframe_message' status='0'>$lang[user_not_exists]</p>"); 
//文件存储路径 
$file_path="./upload/avatar/"; 
//664权限为文件属主和属组用户可读和写,其他用户只读。 
if(is_dir($file_path) != TRUE) mkdir($file_path, 0664) ; 
//定义允许上传的文件扩展名 
$ext_arr = array("gif", "jpg", "jpeg", "png", "bmp"); if (empty($_FILES) === false) { 

//判断检查 

$photo_up_size > 2097152 AND exit("<p class='iframe_message' status='0'>对不起,您上传的照片超过了2M</p>"); 

$_FILES["file"]["error"] > 0 AND exit("<p class='iframe_message' status='0'>文件上传发生错误:".$_FILES["file"]["error"]."</p>"); 

//获得文件扩展名 

$temp_arr = explode(".", $_FILES["file"]["name"]); 

$file_ext = array_pop($temp_arr); 

$file_ext = trim($file_ext); 

$file_ext = strtolower($file_ext); 

//检查扩展名 

if (in_array($file_ext, $ext_arr) === false) { 


exit("<p class='iframe_message' status='0'>上传文件扩展名是不允许的扩展名</p>"); 

} 

//删除目录下相同前缀的文件 

if($dh = opendir($file_path)) { 


while(($file = readdir($dh)) !== false) { 



$file_arr = $file.split('.'); 



if($file_arr[0] == $user['uid']) unlink($file_path.$file); 


} 

} 

//以uid重命名文件 

$new_name = $user['uid'].".".$file_ext; 

//将文件移动到存储目录下 

move_uploaded_file($_FILES["file"]["tmp_name"], $file_path.$new_name); 

//裁剪压缩图片 

clip($file_path.$new_name, $file_path.$new_name, 0, 0, 100, 100); 

clip_thumb($file_path.$new_name, $file_path.$new_name, 100, 100); 

//向数据表写入文件存储信息以便管理 

user_update($user['uid'], array('avatar'=>time())); 

exit("<p class='iframe_message' status='1'>文件上传成功</p>"); 
} else { 

exit("<p class='iframe_message' status='0'>无正确的文件上传</p>"); 
} 
<?php 
function ext($filename) { 
return strtolower(substr(strrchr($filename, '.'), 1)); 
} 
/* 
实例: 
thumb(APP_PATH.'xxx.jpg', APP_PATH.'xxx_thumb.jpg', 200, 200); 
返回: 
array('filesize'=>0, 'width'=>0, 'height'=>0) 
*/ 
function thumb($sourcefile, $destfile, $forcedwidth = 80, $forcedheight = 80) { 
$return = array('filesize'=>0, 'width'=>0, 'height'=>0); 
$imgcomp = 10; 
$destext = ext($destfile); 
if(!in_array($destext, array('gif', 'jpg', 'bmp', 'png'))) { 
return $return; 
} 
$imgcomp = 100 - $imgcomp; 
$imginfo = getimagesize($sourcefile); 
$src_width = $imginfo[0]; 
$src_height = $imginfo[1]; 
if($src_width == 0 || $src_height == 0) { 
return $return; 
} 
$src_scale = $src_width / $src_height; 
$des_scale = $forcedwidth / $forcedheight; 
if(!function_exists('imagecreatefromjpeg')) { 
copy($sourcefile, $destfile); 
$return = array('filesize'=>filesize($destfile), 'width'=>$src_width, 'height'=>$src_height); 
return $return; 
} 
// 按规定比例缩略 
if($src_width <= $forcedwidth && $src_height <= $forcedheight) { 
$des_width = $src_width; 
$des_height = $src_height; 
} elseif($src_scale >= $des_scale) { 
$des_width = ($src_width >= $forcedwidth) ? $forcedwidth : $src_width; 
$des_height = $des_width / $src_scale; 
$des_height = ($des_height >= $forcedheight) ? $forcedheight : $des_height; 
} else { 
$des_height = ($src_height >= $forcedheight) ? $forcedheight : $src_height; 
$des_width = $des_height * $src_scale; 
$des_width = ($des_width >= $forcedwidth) ? $forcedwidth : $des_width; 
} 
switch ($imginfo['mime']) { 
case 'image/jpeg': 
$img_src = imagecreatefromjpeg($sourcefile); 
!$img_src && $img_src = imagecreatefromgif($sourcefile); 
break; 
case 'image/gif': 
$img_src = imagecreatefromgif($sourcefile); 
!$img_src && $img_src = imagecreatefromjpeg($sourcefile); 
break; 
case 'image/png': 
$img_src = imagecreatefrompng($sourcefile); 
break; 
case 'image/wbmp': 
$img_src = imagecreatefromwbmp($sourcefile); 
break; 
default : 
return $return; 
} 
$img_dst = imagecreatetruecolor($des_width, $des_height); 
$img_color = imagecolorallocate($img_dst, 255, 255, 255); 
imagefill($img_dst, 0, 0 ,$img_color); 
imagecopyresampled($img_dst, $img_src, 0, 0, 0, 0, $des_width, $des_height, $src_width, $src_height); 
//$tmpfile = $temp_path.md5($destfile); 
$tmpfile = $destfile; 
switch($destext) { 
case 'jpg': imagejpeg($img_dst, $tmpfile, $imgcomp); break; 
case 'gif': imagegif($img_dst, $tmpfile, $imgcomp); break; 
case 'png': imagepng($img_dst, $tmpfile, version_compare(PHP_VERSION, '5.1.2') == 1 ? 7 : 70); break; 
} 
$r = array('filesize'=>filesize($tmpfile), 'width'=>$des_width, 'height'=>$des_height);; 
copy($tmpfile, $destfile); 
//unlink($tmpfile); 
imagedestroy($img_dst); 
return $r; 
} 
/* 
* 图片裁切 
* 
* @param string $srcname 原图片路径(绝对路径/*.jpg) 
* @param string $forcedheight 裁切后生成新名称(绝对路径/rename.jpg) 
* @param int $sourcefile 被裁切图片的X坐标 
* @param int $destfile 被裁切图片的Y坐标 
* @param int $destext 被裁区域的宽度 
* @param int $imgcomp 被裁区域的高度 
clip('xxx/x.jpg', 'xxx/newx.jpg', 10, 40, 150, 150) 
*/ 
function clip($sourcefile, $destfile, $clipx, $clipy, $clipwidth, $clipheight) { 
$getimgsize = getimagesize($sourcefile); 
if(empty($getimgsize)) { 
return 0; 
} else { 
$imgwidth = $getimgsize[0]; 
$imgheight = $getimgsize[1]; 
if($imgwidth == 0 || $imgheight == 0) { 
return 0; 
} 
} 
if(!function_exists('imagecreatefromjpeg')) { 
copy($sourcefile, $destfile); 
return filesize($destfile); 
} 
switch($getimgsize[2]) { 
case 1 : 
$imgcolor = imagecreatefromgif($sourcefile); 
break; 
case 2 : 
$imgcolor = imagecreatefromjpeg($sourcefile); 
break; 
case 3 : 
$imgcolor = imagecreatefrompng($sourcefile); 
break; 
} 
//$imgcolor = imagecreatefromjpeg($sourcefile); 
$img_dst = imagecreatetruecolor($clipwidth, $clipheight); 
$img_color = imagecolorallocate($img_dst, 255, 255, 255); 
imagefill($img_dst, 0, 0, $img_color); 
imagecopyresampled($img_dst, $imgcolor, 0, 0, $clipx, $clipy, $imgwidth, $imgheight, $imgwidth, $imgheight); 
$tmpfile = $destfile; 
imagejpeg($img_dst, $tmpfile, 100); 
$n = filesize($tmpfile); 
copy($tmpfile, $destfile); 
return $n; 
} 
// 先裁切后缩略,因为确定了,width, height, 不需要返回宽高。 
function clip_thumb($sourcefile, $destfile, $forcedwidth = 80, $forcedheight = 80) { 
// 获取原图片宽高 
$getimgsize = getimagesize($sourcefile); 
if(empty($getimgsize)) { 
return 0; 
} else { 
$src_width = $getimgsize[0]; 
$src_height = $getimgsize[1]; 
if($src_width == 0 || $src_height == 0) { 
return 0; 
} 
} 
$src_scale = $src_width / $src_height; 
$des_scale = $forcedwidth / $forcedheight; 
if($src_width <= $forcedwidth && $src_height <= $forcedheight) { 
$des_width = $src_width; 
$des_height = $src_height; 
$n = clip($sourcefile, $destfile, 0, 0, $des_width, $des_height); 
return filesize($destfile); 
// 原图为横着的矩形 
} elseif($src_scale >= $des_scale) { 
// 以原图的高度作为标准,进行缩略 
$des_height = $src_height; 
$des_width = $src_height / $des_scale; 
$n = clip($sourcefile, $destfile, 0, 0, $des_width, $des_height); 
if($n <= 0) return 0; 
$r = thumb($destfile, $destfile, $forcedwidth, $forcedheight); 
return $r['filesize']; 
// 原图为竖着的矩形 
} else { 
// 以原图的宽度作为标准,进行缩略 
$des_width = $src_width; 
$des_height = $src_width / $des_scale; 
$n = clip($sourcefile, $destfile, 0, 0, $des_width, $des_height); 
if($n <= 0) return 0; 
$r = thumb($destfile, $destfile, $forcedwidth, $forcedheight); 
return $r['filesize']; 
} 
} 
?>

我们php中设置返回内容,会发现,在出现相应情况后,返回内容出现在页面的iframe中,所以我们设定了相应的class,以便前端获得返回内容,做出相应处理。clip(),clip_thumb()为裁剪图片函数,可压缩图片大小,裁取图片以左上角为起点,长宽为100的正方形。

js:

var jsubmit_file = jinput.filter('[name="submit_file"]'); 
var jfile = jinput.filter('[name="file"]'); 
var jiframe = $('#iframe'); 
var jthumb = $('.thumb'); 
var type = ''; 
jfile.on('change', function() { 
var path = jfile.val(); 
var file_arr = path.split('.'); 
type = file_arr[file_arr.length-1]; 
jsubmit_file.trigger('click'); 
}); 
jiframe.on('load', function() { 
var jiframe_message = $(window.frames['iframe'].document).find('.iframe_message'); 
if(jiframe_message.attr('status') != 0) { 
var url = this.contentWindow.location.href; 
var url_arr = url.split('='); 
jthumb.attr('src', url_arr[1] + '.' + type); 
} 
alert(jiframe_message.text()); 
});

这样基本就实现了图片上传、上传结果提示、即时显示上传的最新头像这几个功能,网上有各种插件,虽然功能丰富,就是体积太大,这个看我们取舍了。
PHP 相关文章推荐
php数据结构 算法(PHP描述) 简单选择排序 simple selection sort
Aug 09 PHP
探讨file_get_contents与curl效率及稳定性的分析
Jun 06 PHP
php对二维数组进行排序的简单实例
Dec 19 PHP
PHP中的Memcache详解
Apr 05 PHP
php中socket通信机制实例详解
Jan 03 PHP
PHP6连接SQLServer2005的三部曲
Apr 15 PHP
Zend Framework分发器用法示例
Dec 11 PHP
thinkPHP实现的省市区三级联动功能示例
May 05 PHP
php实现查询功能(数据访问)
May 23 PHP
PHP中number_format()函数的用法讲解
Apr 08 PHP
php中目录操作opendir()、readdir()及scandir()用法示例
Jun 08 PHP
PHP isset empty函数相关面试题及解析
Dec 11 PHP
php数组查找函数in_array()、array_search()、array_key_exists()使用实例
Apr 29 #PHP
PHP的MVC模式实现原理分析(一相简单的MVC框架范例)
Apr 29 #PHP
php中使用getimagesize获取图片、flash等文件的尺寸信息实例
Apr 29 #PHP
PHP include任意文件或URL介绍
Apr 29 #PHP
php调用google接口生成二维码示例
Apr 28 #PHP
php将字符串转化成date存入数据库的两种方式
Apr 28 #PHP
php使用array_rand()函数从数组中随机选择一个或多个元素
Apr 28 #PHP
You might like
jQuery中的RadioButton,input,CheckBox取值赋值实现代码
2014/02/18 PHP
PHP实现数据分页显示的简单实例
2016/05/26 PHP
php使用file函数、fseek函数读取大文件效率对比分析
2016/11/04 PHP
php事件驱动化设计详解
2016/11/10 PHP
针对thinkPHP5框架存储过程bug重写的存储过程扩展类完整实例
2018/06/16 PHP
PHP实现的装箱算法示例
2018/06/23 PHP
对xmlHttp对象方法和属性的理解
2011/01/17 Javascript
多个js与css文件的合并方法详细说明
2012/12/26 Javascript
jQuery中:lt选择器用法实例
2014/12/29 Javascript
javascript实现百度地图鼠标滑动事件显示、隐藏
2015/04/02 Javascript
AngularJS基础知识笔记之过滤器
2015/05/10 Javascript
深入解析JavaScript中函数的Currying柯里化
2016/03/19 Javascript
Bootstrap编写一个在当前网页弹出可关闭的对话框 非弹窗
2016/06/30 Javascript
Vue2.0实现将页面中表格数据导出excel的实例
2017/08/09 Javascript
JS实现静态页面搜索并高亮显示功能完整示例
2017/09/19 Javascript
vue中使用localstorage来存储页面信息
2017/11/04 Javascript
详细分析jsonp的原理和实现方式
2017/11/20 Javascript
图片懒加载imgLazyLoading.js使用详解
2020/09/15 Javascript
JavaScript原型对象、构造函数和实例对象功能与用法详解
2018/08/04 Javascript
layui实现三级导航菜单
2019/07/26 Javascript
微信小程序修改checkbox的样式代码实例
2020/01/21 Javascript
基于Python的身份证号码自动生成程序
2014/08/15 Python
python结合opencv实现人脸检测与跟踪
2015/06/08 Python
Python常用的爬虫技巧总结
2016/03/28 Python
python中通过预先编译正则表达式提高效率
2017/09/25 Python
python tools实现视频的每一帧提取并保存
2020/03/20 Python
python 返回一个列表中第二大的数方法
2019/07/09 Python
Django如何简单快速实现PUT、DELETE方法
2019/07/24 Python
如何用tempfile库创建python进程中的临时文件
2021/01/28 Python
美国精品家居用品网站:US-Mattress
2016/08/24 全球购物
Mytheresa英国官网:拥有160多个奢侈品品牌
2016/10/09 全球购物
以思科路由器为例你写下单臂路由的配置命令
2013/08/03 面试题
《雨霖铃》教学反思
2014/02/22 职场文书
2014年派出所工作总结
2014/11/21 职场文书
稽核岗位职责
2015/02/10 职场文书
Java8 Stream API 提供了一种高效且易于使用的处理数据的方式
2022/04/13 Java/Android