文件上传分为客户端和服务器端
客户端可以通过form表单进行上传
客户端使用html表单进行上传
enctype = "multipart/form-data"用来指定表单编码数据方式
method = "POST"指明发送数据的方法
<form action = "upload.php" method = "POST" enctype = "multipart/form-data">
<input type = "hidden" name = "MAXN_FILIE_SIZE" value = "100000">
选择文件:<input type = "file" name = "myFile">
<input type = "submit" value = "上传文件">
</form>
最主要的就是type="file"的<input>标签
服务器端
1 <!-- 2 简单的文件上传的PHP脚本 3 -> 4 <?php 5 $allowtype = array("gif","png","jpg"); 6 $size = 1000000; 7 $path = "./upload"; 8 9 if($_FILES['myfile']['error'] > 0){ 10 echo "文件上传错误"; 11 switch($_FILES['myfile']['error']){ 12 case 1 :die('上传文件大小超过了PHP配置文件中的约定值'); 13 case 2 :die('上传文件大小超过了浏览器中的约定值'); 14 case 3 :die('文件只被上传部分'); 15 case 4 :die('没有上传的文件'); 16 default :die('其它错误'); 17 } 18 } 19 20 $hz = array_pop(explode(".",$_FILES['myfile']['name'])); 21 if(!in_array($hz,$allowtype)){ 22 die("这个后缀是<b>{$hz}</b>不是允许的类型"); 23 } 24 25 if($_FILES['myfile']['size'] > $size){ 26 die("超过了允许的<b>$size</b>字节大小"); 27 } 28 29 $filename = date("YmdHis").rand(100,999).".".$hz; 30 31 if(is_uploaded_file($_FILES['myfile']['tmp_name'])){ 32 if(!move_uploaded_file($_FILES['myfile']['tmp_name'],$path.'/'.$filename)){ 33 die("不能将文件移动到指定目录"); 34 } 35 }else{ 36 die("上传文件:{$_FILES['myfile']['name']}不是一个合法文件"); 37 } 38 39 echo "文件{$myfile}上传成功,保存在目录{$path}中,大小为{$_FILES['myfile']['size']}字节"; 40 ?>
用POST方法将文件上传时主要运用到的是$_FILES[]全局数组
$_FILES是一个二维数组 $_FILES['myfile']['name'] $_FILES['myfile']['tmp_name'] $_FILES['myfile']['size'] $_FILES['myfile']['error'] $_FILES['myfile']['type']
用到的函数有:is_uploaded_file() move_uploaded_file()
多个文件上传时只需要运用myfile[]数组即可 此时的$_FILES是三维数组
1 <form action = "upload.php" method = "POST" enctype = "multipart/form-data"> 2 <input type = "hidden" name = "MAXN_FILIE_SIZE" value = "100000"> 3 选择文件1:<input type = "file" name = "myFile[]"> 4 选择文件2:<input type = "file" name = "myFile[]"> 5 选择文件3:<input type = "file" name = "myFile[]"> 6 <input type = "submit" value = "上传文件"> 7 </form>