- 重命名 : 为防止文件名重复, 使用的规则是
年月日时分秒 + 随机数序
- Ajax & callback : use jquery.form.js
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="/jquery.min.js"></script> <script src="/jquery.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 sizeif( 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 http://xiaohudie.net. Any posts here is one hundred percent original, so please keep my link so as not to hurt this pretty girl. -
发现你现在博客打开越来越快了,是新的机子好?
@airoschou 蹭大发的 哈哈哈
@airoschou 小蝴蝶没有你那样好看的demo。。。
果断围观飘过!
@陈羽凡博客 你好,我是海泉啊!
@胡海泉博客 。。。。。。海泉,到楼上来喝杯茶,探讨一下人生。
@陈羽凡博客 你小子和我刚结束上海演唱会,就来这评论了,白百合知道吗?如果知道,我可帮不了你了!
纯代码模式开启。。
@梦月酱 int mode = coding; 哈哈