问题:上传后判断文件大小,浪费带宽,增加服务器负担?
可以使用ajax文件上传,
在客户端判断大小,需要浏览器分析出文件的大小
浏览器判断硬盘的上文件的大小?
不能,JS不能操作本地文件
File 域是没有默认值
由单文件上传到多文件上传遍历数组
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Document</title> </head> <body> <form action="07.php" method="POST" enctype="multipart/form-data"> 用户名: <input type="text" name="username"/><br/> 头像:<input type="file" name="pic"/><br/> 简历:<input type="file" name="jianli"/><br/> 附件:<input type="file" name="fujian"/><br/> <input type="submit" value="提交"/> </form> </body> </html> |
Array ( [pic] => Array ( [name] => 0s08209102362014312190547.jpg [type] => p_w_picpath/jpeg [tmp_name] => C:\wamp\tmp\phpE4C2.tmp [error] => 0 [size] => 27423 ) [jianli] => Array ( [name] => 1 (2).jpg [type] => p_w_picpath/jpeg [tmp_name] => C:\wamp\tmp\phpE4C3.tmp [error] => 0 [size] => 113477 ) [fujian] => Array ( [name] => 1.jpg [type] => p_w_picpath/jpeg [tmp_name] => C:\wamp\tmp\phpE4D3.tmp [error] => 0 [size] => 108676 ) ) |
因此只需把大的$_FILES数组遍历一遍即可
<?php /*计算并创建目录*/ function mk_dir(){ $dir = date("md/i",time()); if (is_dir('./'.$dir)) { return $dir; }else{ mkdir('./'.$dir,0777,true); return $dir; } } /*获取文件后缀*/ function getExt($file){ $tmp = explode('.', $file); return end($tmp); } /*获取随机文件名*/ function randName(){ $str = 'abcdefghijklmnpqrstuvwxyz23456789'; return substr(str_shuffle($str), 0,6); } //移动文件 foreach($_FILES as $k=>$v){ //拼接文件路径 $path = './'.mk_dir().'/'.randName().'.'.getExt($v['name']); if ($v['error'] != 0) { echo $k,"上传失败<br/>"; echo "错误代码是:",$v['error'],'<br/>'; continue; } if (move_uploaded_file($v['tmp_name'], $path)) { echo $k,"成功<br/>"; }else{ echo $k,"失败<br/>"; } } ?> |
注意:
表单的陷阱,为了上传多个文件,在name的命名上采用数组形式命名
如采用pic[]
头像:<input type="file" name="pic[]"/><br/> 简历:<input type="file" name="pic[]"/><br/> 附件:<input type="file" name="pic[]"/><br/> |
相当于 pic[0] pic[1] pic[2]
Array ( [pic] => Array ( [name] => Array ( [0] => Login.php [1] => Review.php [2] => Send.php ) [type] => Array ( [0] => application/php [1] => application/php [2] => application/php ) [tmp_name] => Array ( [0] => C:\wamp\tmp\phpED59.tmp [1] => C:\wamp\tmp\phpED5A.tmp [2] => C:\wamp\tmp\phpED5B.tmp ) [error] => Array ( [0] => 0 [1] => 0 [2] => 0 ) [size] => Array ( [0] => 571 [1] => 636 [2] => 563 ) ) ) |