php实现文件上传及头像预览功能

2017-04-02 10:24:17  php上传预览

php文件上传原理是通过form表单的enctype="multipart/form-data"属性将文件临时放到wamp文件夹中的tmp目录下,再通过后台php程序将文件保存在体统中。

html代码:

<form action="shangchuan.php" method="post" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" value="上传" /> </form>

后台处理界面(shangchuan.php):

有以下几点需要注意

1.控制上传文件的类型
2.控制上传文件的大小
3.防止文件名重复
修改保存的文件名
用户名+时间戳+随机数+文件名
流水号

使用文件夹要提前建好路径。

4.保存文件

//判断文件上传是否出错 if($_FILES["file"]["error"]) { echo $_FILES["file"]["error"]; } else { //控制上传文件的类型,大小 if(($_FILES["file"]["type"]=="image/jpg" || $_FILES["file"]["type"]=="image/jpg") && $_FILES["file"]["size"]<1024000) { //找到文件存放的位置 $filename = "./file/".date("YmdHis").$_FILES["file"]["name"]; //转换编码格式 $filename = iconv("UTF-8","gb2312",$filename); //判断文件是否存在 if(file_exists($filename)) { echo "该文件已存在!"; } else { //保存文件 move_uploaded_file($_FILES["file"]["tmp_name"],$filename); } } else { echo "文件类型不正确!"; } }

点击上传后文件就保存在系统的指定路径下。

php实现文件上传及头像预览功能

保存后按照指定方法重命名文件名:

php实现文件上传及头像预览功能

头像上传预览

原理:在html界面做一个头像大小的div,设置上传头像的背景,在div里面做一个上传文件的input,透明度设置为0.

这样,点击这个div就可以跟上传的效果相同。

<title>无标题文档</title> <style type="text/css"> #yl{ width:200px; height:300px; background-image:url(img/11.jpg); background-size:200px 300px;} #file{ width:200px; height:300px; float:left; opacity:0;} </style> </head> <body> <form action="chuli.php" method="post" enctype="multipart/form-data" target="shangchuan"> <input type="hidden" name="tp" value="" /> <div> <input type="file" name="file" onchange="document.getElementById('sc').submit()" /> </div> </form> <iframe style="display:none" name="shangchuan"> </iframe> </body> <script type="text/javascript"> //回调函数,调用该方法传一个文件路径,该变背景图 function showimg(url) { var div = document.getElementById("yl"); div.style.backgroundImage = "url("+url+")"; document.getElementById("tp").value = url; } </script> </html>

php处理界面(chuli.php):

<?php if($_FILES["file"]["error"]) { echo $_FILES["file"]["error"]; } else { if(($_FILES["file"]["type"]=="image/jpg" || $_FILES["file"]["type"]=="image/jpg")&& $_FILES["file"]["size"]<1024000) { $fname = "./img/".date("YmdHis").$_FILES["file"]["name"]; $filename = iconv("UTF-8","gb2312",$fname); if(file_exists($filename)) { echo "<script>alert('该文件已存在!');</script>"; } else { move_uploaded_file($_FILES["file"]["tmp_name"],$filename); unlink($_POST["tp"]); echo "<script>parent.showimg('{$fname}');</script>"; } } }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

php实现文件上传及头像预览功能》阅读地址:http://www.haoshilao.net/15103/

最新图文教程: