重命名 : 为防止文件名重复, 使用的规则是 年月日时分秒 + 随机数序 Ajax callback : use jquery.form.js html+js: htmlbody!--表单--form action="upload_file.php" method="post" enctype="multipart/form-data" id="xhdform"input type="file" name="file
年月日时分秒 + 随机数序
html+js:
<html>
<body>
<!--表单-->
<form action="upload_file.php" method="post" enctype="multipart/form-data" id="xhdform">
<input type="file" name="file" id="file" />
<input type="hidden" name="xxx" />
<input type="submit" name="submit" value="Submit" />
</form>
<div id="ooo"> <!--where to callback--> </div>
<script src="/imgr?src=http%3A%2F%2Fxiaohudie.net%2Fjquery.min.js"></script>
<script src="/imgr?src=http%3A%2F%2Fxiaohudie.net%2Fjquery.form.js"></script>
<script type="text/javascript">
//JQ
$(document).ready(function() {
$('#xhdform').submit(function() {
var options = {
target: '#ooo', //where to callback
url: 'upload_file.php', //form的action地址
type: 'post',
success: function() {
$('#xxx').val($('#ooo').text()); //what to callback
}
};
$(this).ajaxSubmit(options);
return false;
});
});
</script>
</body>
</html>upload_file.php:
<?php
$folder = 'upload/';
if (! file_exists ( $folder )) {mkdir ( $folder );}//新增: create folder "upload"
if ((($_FILES["file"]["type"] == "image/gif") || ($_FILES["file"]["type"] == "image/jpg") || ($_FILES["file"]["type"] == "image/png")) // 允许上传的文件类型
&& ($_FILES["file"]["size"] < 20000)) // max size
if( preg_match( "#^image/((?:gif)|(?:jpg)|(?:jpeg)|(?:png))$#is", $_FILES["file"]["type"], $match ) && ($_FILES["file"]["size"] < 2097152) )
// 20000差不多是20kb太小了, 刚才修改了一下, 改成2M; 另外此行preg_match和上面["file"]["type"]==的效果一样
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br />";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
if (file_exists("upload/" . $_FILES["file"]["name"])) // if file already exists
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
// rename rule begin ~~~~ xiaohudie
for ( $i=0; $i<10; $i++ )
$rand = substr($rand2,mt_rand(0,strlen($rand2)-1),1);
$rand2 = '1234567890abcdefghijklmnopgrstuvwxyz';
$id = date("YmdHis").'_'.$rand; //输出格式例如: 20130503112737_npcajvurig
move_uploaded_file( $_FILES["file"]["tmp_name"], "upload/" . $id .".jpg" ); //在upload文件夹保存图片并重命名, 添加.jpg后缀
echo "Stored in: " . "upload/" . $id .".jpg";
}
}
}
else
{
echo "Invalid file";
}
?>代码写多了感觉自己中文跟不上节奏了, 专注装逼十九年其实我想用全英文写注释的
file_upload is coded by xiaohudie. Any posts here is one hundred percent original, so please keep my link so as not to hurt this pretty girl
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号