php实现头像上传预览的功能实例详解

怪我咯
发布: 2023-03-12 15:44:02
原创
1782 人浏览过

这篇文章主要为大家详细介绍了php实现头像上传预览功能的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了php实现头像上传预览功能的具体代码,供大家参考,具体内容如下

主页面1.php

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>上传头像</title>
<style type="text/css">
  *{
    font-family:"微软雅黑";}
  #zong{
    /*border:1px solid black;*/
    position:relative;
    width:52%;
    height:500x;
    left:24%}
  .nr{
    float:left;
    margin-right:30px;}
  #yl{width:240px; height:240px; background-size:240px 240px;}
  #file{width:240px; height:240px; float:left; opacity:0;}
</style>
</head>

<body>

<p id="zong">
<form id="sc" action="2.php" method="post" enctype="multipart/form-data" target="shangchuan">
  
  <input type="hidden" name="tp" value="" id="tp" />
  
  <p id="yl" style="background-image:url(./image/1.jpg)" class="nr">//头像显示的位置
    <input type="file" name="file" id="file" onchange="document.getElementById(&#39;sc&#39;).submit()" />
  </p>
  <p class="nr">
  </p> 
</form>

<iframe style="display:none" name="shangchuan" id="shangchuan">
</iframe>

</p>
</body>

<script type="text/javascript">

//回调函数,调用该方法传一个文件路径,改变背景图
function showimg(url)
{
  var p = document.getElementById("yl");
  p.style.backgroundImage = "url("+url+")";
  
  document.getElementById("tp").value = url;
}

</script>

</html>
登录后复制

处理页面2.php

<?php
session_start();
$uid = $_SESSION["uid"];
if($_FILES["file"]["error"])
{
  echo $_FILES["file"]["error"];
}
else
{
  if(($_FILES["file"]["type"]=="image/jpeg" || $_FILES["file"]["type"]=="image/png")&& $_FILES["file"]["size"]<1024000)
  {
    $fname = "./a/image/".date("YmdHis").$_FILES["file"]["name"];  //头像存储的路径
    
    $filename = iconv("UTF-8","gb2312",$fname);
    
    if(file_exists($filename))
    {
      echo "<script>alert(&#39;该文件已存在!&#39;);</script>";
    }
    else
    {
      move_uploaded_file($_FILES["file"]["tmp_name"],$filename);
      
      unlink($_POST["tp"]);
      echo "<script>parent.showimg(&#39;{$fname}&#39;);</script>";
    }
    
  }
}
登录后复制

打开显示:

点击图片位置弹出选择框:

选择图片完成后:

以上是php实现头像上传预览的功能实例详解的详细内容。更多信息请关注PHP中文网其他相关文章!

相关标签:
来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!