《PHP實戰(zhàn):php實現(xiàn)文件上傳及頭像預覽功能》要點:
本文介紹了PHP實戰(zhàn):php實現(xiàn)文件上傳及頭像預覽功能,希望對您有用。如果有疑問,可以聯(lián)系我們。
PHP編程php文件上傳原理是通過form表單的enctype="multipart/form-data"屬性將文件臨時放到wamp文件夾中的tmp目錄下,再通過后臺php程序?qū)⑽募4嬖隗w統(tǒng)中.
PHP編程html代碼:
PHP編程
<form action="shangchuan.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="上傳" />
</form>
PHP編程后臺處理界面(shangchuan.php):
PHP編程有以下幾點需要注意:
PHP編程1.控制上傳文件的類型
2.控制上傳文件的大小
3.防止文件名重復
修改保存的文件名
用戶名+時間戳+隨機數(shù)+文件名
流水號
PHP編程使用文件夾要提前建好路徑.
PHP編程4.保存文件
PHP編程
//判斷文件上傳是否出錯
if($_FILES["file"]["error"])
{
echo $_FILES["file"]["error"];
}
else
{
//控制上傳文件的類型,大小
if(($_FILES["file"]["type"]=="image/jpeg" || $_FILES["file"]["type"]=="image/png") && $_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編程點擊上傳后文件就保存在系統(tǒng)的指定路徑下.
PHP編程
PHP編程保存后按照指定方法重命名文件名:
PHP編程
PHP編程頭像上傳預覽
PHP編程原理:在html界面做一個頭像大小的div,設置上傳頭像的背景,在div里面做一個上傳文件的input,透明度設置為0.
PHP編程這樣,點擊這個div就可以跟上傳的效果相同.
PHP編程
<title>無標題文檔</title>
<style type="text/css">
#yl{ width:200px; height:300px; background-image:url(img/11.png); background-size:200px 300px;}
#file{ width:200px; height:300px; float:left; opacity:0;}
</style>
</head>
<body>
<form id="sc" action="chuli.php" method="post" enctype="multipart/form-data" target="shangchuan">
<input type="hidden" name="tp" value="" id="tp" />
<div id="yl">
<input type="file" name="file" id="file" onchange="document.getElementById('sc').submit()" />
</div>
</form>
<iframe style="display:none" name="shangchuan" id="shangchuan">
</iframe>
</body>
<script type="text/javascript">
//回調(diào)函數(shù),調(diào)用該方法傳一個文件路徑,該變背景圖
function showimg(url)
{
var div = document.getElementById("yl");
div.style.backgroundImage = "url("+url+")";
document.getElementById("tp").value = url;
}
</script>
</html>
PHP編程php處理界面(chuli.php):
PHP編程
<?php
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 = "./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編程以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持維易PHP.
轉載請注明本頁網(wǎng)址:
http://www.snjht.com/jiaocheng/1984.html