热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

这篇文章主要介绍了php+js实现的上传头像界面无跳转,示例中用到了iframe,需要的朋友可以参考下
上传头像,界面无跳转的方式很多,我用的是加个iframe那种。下面直接上代码。

html:

代码如下:


//route 为后端接口
//upload/avatar 为上传的头像的保存地址
//imgurl=/upload/avatar/ 这里最后的是为了后面用js实现即时显示最新的更换后的头像用的,参照下面的js部分的代码
//头像保存名称为uid.type,如1.jpg,2.png等
//$user['avatar'] 用户如果上传过头像,该用户数据库中的avatar字段将赋予时间戳,否则为空
" method="post" id="upload_form">




php:

代码如下:


$token = param('token');
$user = user_from_token($token);
!$user AND exit("

$lang[user_not_exists]

");
//文件存储路径
$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("

对不起,您上传的照片超过了2M

");
  $_FILES["file"]["error"] > 0 AND exit("

文件上传发生错误:".$_FILES["file"]["error"]."

");
  //获得文件扩展名
  $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("

上传文件扩展名是不允许的扩展名

");
  }
  //删除目录下相同前缀的文件
  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("

文件上传成功

");
} else {
  exit("

无正确的文件上传

");
}


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());
});


这样基本就实现了图片上传、上传结果提示、即时显示上传的最新头像这几个功能,网上有各种插件,虽然功能丰富,就是体积太大,这个看我们取舍了。
推荐阅读
  • 如何实现织梦DedeCms全站伪静态
    本文介绍了如何通过修改织梦DedeCms源代码来实现全站伪静态,以提高管理和SEO效果。全站伪静态可以避免重复URL的问题,同时通过使用mod_rewrite伪静态模块和.htaccess正则表达式,可以更好地适应搜索引擎的需求。文章还提到了一些相关的技术和工具,如Ubuntu、qt编程、tomcat端口、爬虫、php request根目录等。 ... [详细]
  • Monkey《大话移动——Android与iOS应用测试指南》的预购信息发布啦!
    Monkey《大话移动——Android与iOS应用测试指南》的预购信息已经发布,可以在京东和当当网进行预购。感谢几位大牛给出的书评,并呼吁大家的支持。明天京东的链接也将发布。 ... [详细]
  • 本文介绍了lua语言中闭包的特性及其在模式匹配、日期处理、编译和模块化等方面的应用。lua中的闭包是严格遵循词法定界的第一类值,函数可以作为变量自由传递,也可以作为参数传递给其他函数。这些特性使得lua语言具有极大的灵活性,为程序开发带来了便利。 ... [详细]
  • GetWindowLong函数
    今天在看一个代码里头写了GetWindowLong(hwnd,0),我当时就有点费解,靠,上网搜索函数原型说明,死活找不到第 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • 基于layUI的图片上传前预览功能的2种实现方式
    本文介绍了基于layUI的图片上传前预览功能的两种实现方式:一种是使用blob+FileReader,另一种是使用layUI自带的参数。通过选择文件后点击文件名,在页面中间弹窗内预览图片。其中,layUI自带的参数实现了图片预览功能。该功能依赖于layUI的上传模块,并使用了blob和FileReader来读取本地文件并获取图像的base64编码。点击文件名时会执行See()函数。摘要长度为169字。 ... [详细]
  • PHP玩家基地系统毕业设计(附源码、运行环境)的用户登录界面、游戏管理和玩家作品管理
    本文介绍了一个PHP玩家基地系统的毕业设计,包括用户登录界面、游戏管理和玩家作品管理等功能。附带源码和运行环境,并提供免费赠送本源代码和数据库的方式,请私信获取详细信息。摘要共计约XXX字。 ... [详细]
  • 本文介绍了《中秋夜作》的翻译及原文赏析,以及诗人当代钱钟书的背景和特点。通过对诗歌的解读,揭示了其中蕴含的情感和意境。 ... [详细]
  • Lodop中特殊符号打印设计和预览样式不同的问题解析
    本文主要解析了在Lodop中使用特殊符号打印设计和预览样式不同的问题。由于调用的本机ie引擎版本可能不同,导致在不同浏览器下样式解析不同。同时,未指定文字字体和样式设置也会导致打印设计和预览的差异。文章提出了通过指定具体字体和样式来解决问题的方法,并强调了以打印预览和虚拟打印机测试为准。 ... [详细]
  • 本文详细介绍了SQL日志收缩的方法,包括截断日志和删除不需要的旧日志记录。通过备份日志和使用DBCC SHRINKFILE命令可以实现日志的收缩。同时,还介绍了截断日志的原理和注意事项,包括不能截断事务日志的活动部分和MinLSN的确定方法。通过本文的方法,可以有效减小逻辑日志的大小,提高数据库的性能。 ... [详细]
  • 本文介绍了Python高级网络编程及TCP/IP协议簇的OSI七层模型。首先简单介绍了七层模型的各层及其封装解封装过程。然后讨论了程序开发中涉及到的网络通信内容,主要包括TCP协议、UDP协议和IPV4协议。最后还介绍了socket编程、聊天socket实现、远程执行命令、上传文件、socketserver及其源码分析等相关内容。 ... [详细]
  • 本文介绍了在Python3中如何使用选择文件对话框的格式打开和保存图片的方法。通过使用tkinter库中的filedialog模块的asksaveasfilename和askopenfilename函数,可以方便地选择要打开或保存的图片文件,并进行相关操作。具体的代码示例和操作步骤也被提供。 ... [详细]
  • 本文描述了作者第一次参加比赛的经历和感受。作者是小学六年级时参加比赛的唯一选手,感到有些紧张。在比赛期间,作者与学长学姐一起用餐,在比赛题目中遇到了一些困难,但最终成功解决。作者还尝试了一款游戏,在回程的路上感到晕车。最终,作者以110分的成绩取得了省一会的资格,并坚定了继续学习的决心。 ... [详细]
  • 搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的详细步骤
    本文详细介绍了搭建Windows Server 2012 R2 IIS8.5+PHP(FastCGI)+MySQL环境的步骤,包括环境说明、相关软件下载的地址以及所需的插件下载地址。 ... [详细]
  • 关羽败走麦城时路过马超封地 马超为何没有出手救人
    对当年关羽败走麦城,恰好路过马超的封地,为啥马超不救他?很感兴趣的小伙伴们,趣历史小编带来详细的文章供大家参考。说到英雄好汉,便要提到一本名著了,没错,那就是《三国演义》。书中虽 ... [详细]
author-avatar
呼吸乱了的声音_648
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有