上传头像,界面无跳转的方式很多,我用的是加个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+js的更多相关文章

  1. Android基础之——startActivityForResult启动界面并返回数据,上传头像

    在android应用的开发过程中,常常会出现启动一个界面后填写部分内容后带着数据返回启动前的界面,最典型的应用就是登录过程.在非常多应用程序的模块中,都有"我的"这个模块,在未登录 ...

  2. PHP+Ajax+plupload无刷新上传头像代码

    很简单的一款PHP+Ajax+plupload无刷新上传头像代码,兼容性很好,可以直接拿来用.你可以自定义各种类型的文件.本实例中只能上传"jpg", "png" ...

  3. python 全栈开发,Day86(上传文件,上传头像,CBV,python读写Excel,虚拟环境virtualenv)

    一.上传文件 上传一个图片 使用input type="file",来上传一个文件.注意:form表单必须添加属性enctype="multipart/form-data ...

  4. 20-1 django上传文件和项目里上传头像如何查看

    一 普通上传方式 1 views def upload(request): if request.method == "POST": # print(request.POST) # ...

  5. day105:Mofang:设置页面初始化&更新头像/上传头像&设置页面显示用户基本信息

    目录 1.设置页面初始化 2.更新头像 1.点击头像进入更新头像界面 2.更新头像页面初始化 3.更新头像页面CSS样式 4.头像上传来源选择:相册/相机 5.调用api提供的本地接口从相册/相机提取 ...

  6. 上传头像,layui上传图片

    layui上传与bootstrap上传相似,只是不需要下插件, layui自带的已够用 先看一下前台界面,这里是用到的上传头像 先点击开始上传,头像上传至服务器中, 返回json添加至form表单中, ...

  7. jQuery 自制上传头像插件-附带Demo实例(ajaxfileupload.js第三弹)

    这篇文章主要是对前两篇关于ajaxfileupload.js插件的文章 <ASP.NET 使用ajaxfileupload.js插件出现上传较大文件失败的解决方法(ajaxfileupload. ...

  8. swift上传头像

    很久没有写博客了,今天特地写了这个,也是一边仿照别人写的demo,注释部分都是需要的.需要的同学可以参考一下. @IBAction func headImageBtnPage(){  //上传头像 / ...

  9. html5 上传头像的裁剪

    本示例使用HTML5 canvas,简单的编写了上传头像的裁剪效果,移动端支持拖拽后裁剪, 虽然样式不好看,但是功能还算全: 下图为裁剪后的效果: html部分: <!DOCTYPE html& ...

随机推荐

  1. java复习1 java简单介绍

    在学校的时候.学JAVA学的模棱两可,半知半解.工作以后给我带来了非常大的困扰,所以我须要在学一遍.如今就開始吧... . java[1]是一种能够撰写跨平台应用软件的面向对象的程序设计语言,是由Su ...

  2. yii 数据库迁移

    在我们开发程序的过程中,数据库的结构也是不断调整的.我们的开发中要保证代码和数据库库的同步.因为我们的应用离不开数据库.例如: 在开发过程中,我们经常需要增加一个新的表,或者我们后期投入运营的产品,可 ...

  3. 代理模式及其在spring与struts2中的体现

    代理模式 代理模式有三个角色组成: 1.抽象主题角色:声明了真实主题和代理主题的共同接口. 2.代理主题角色:内部包含对真实主题的引用,并且提供和真实主题角色相同的接口. 3.真实主题角色:定义真实的 ...

  4. [010]转+修正---C++的贪吃蛇程序(未用面向对象封装)

    在网上看到一段贪吃蛇程序,自己心痒下了下来又稍微做了一点修改. 没有用面向对象的方式来进行封装,下次准备试试. 需要在windows环境下进行编译 #include<iostream> # ...

  5. Vmware中为Mac Os安装vmtools

    成功方法: 1. 在VMWare中点击edit this virtual machine 2. 添加CD/DVD,使用iso,找到那个darwin.iso 3. 在setting里面,点击CD/DVD ...

  6. linux vi 撤销重做于前进后退--转

    在vi中按u可以撤销一次操作 u   撤销上一步的操作Ctrl+r 恢复上一步被撤销的操作 注意:如果你输入“u”两次,你的文本恢复原样,那应该是你的Vim被配置在Vi兼容模式了.重做如果你撤销得太多 ...

  7. eclipse.ini配置eclipse的启动参数

    Eclipse的启动由$ECLIPSE_HOME/eclipse.ini控制,如果$ECLIPSE_HOME 没有被定义,则Eclipse安装目录下的默认eclipse.ini会生效. eclipse ...

  8. Objective-C,复合类,Composition

     复合类 5.复合类现实中,复杂的对象都是由较小和较为简单的对象构成:由简单对象创建复杂对象的过程称作合成.合成通常使用在有has-a关系的对象:通常的基本数据类型可以满足构造简单和小的对象.为了从小 ...

  9. MATLAB 误差函数erf(x)

    误差函数: 1.误差函数定义为:   它的性质如下: 2 互补误差函数定义为: 它具有如下性质: 下表给出了误差函数的部分数值: 0.00 0.00000 0.05 0.05637 0.10 0.11 ...

  10. JavaScript高级程序设计(第三版)学习笔记20、21、23章

    第20章,JSON JSON(JavaScript Object Notation,JavaScript对象表示法),是JavaScript的一个严格的子集. JSON可表示一下三种类型值: 简单值: ...