input标签file类型,选择多个文件进行上传

来源:互联网 发布:手机淘宝新用户注册 编辑:程序博客网 时间:2024/05/21 09:37

html页面

[html] view plain copy 在CODE上查看代码片派生到我的代码片
  1. <!DOCTYPE html>  
  2. <html>  
  3.     <head>  
  4.         <meta charset="UTF-8"/>  
  5.         <title>xhr2</title>  
  6.     </head>  
  7.     <body>      
  8.         <div style="text-align:center;margin:100px">        
  9.             <input type="file" id="file" name="file" multiple="multiple">  
  10.             <button onclick="xhr2()">多文件上传</button>  
  11.         </div>          
  12.         <script>  
  13.         function xhr2(){  
  14.             var xhr = new XMLHttpRequest();//第一步  
  15.             //定义表单变量  
  16.             var file = document.getElementById('file').files;  
  17.             //console.log(file.length);  
  18.             //新建一个FormData对象  
  19.             var formData = new FormData(); //++++++++++  
  20.             //追加文件数据  
  21.             for(i=0;i<file.length;i++){    
  22.                  formData.append("file["+i+"]", file[i]); //++++++++++  
  23.             }   
  24.             //formData.append("file", file[0]); //++++++++++  
  25.               
  26.             //post方式  
  27.             xhr.open('POST', 'xhr2.php'); //第二步骤  
  28.             //发送请求  
  29.             xhr.send(formData);  //第三步骤  
  30.             //ajax返回  
  31.             xhr.onreadystatechange = function(){ //第四步  
  32.             if ( xhr.readyState == 4 && xhr.status == 200 ) {  
  33.               console.log( xhr.responseText );  
  34.             }  
  35.           };  
  36.             //设置超时时间  
  37.             xhr.timeout = 100000;  
  38.             xhr.ontimeout = function(event){  
  39.             alert('请求超时!');  
  40.           }   
  41.         }  
  42.         </script>  
  43.     </body>  
  44. </html>  

php处理页面
[php] view plain copy 在CODE上查看代码片派生到我的代码片
  1. <?php  
  2. print_r($_FILES["file"]);  
  3.   
  4. for($i=0;$i<count($_FILES["file"]['name']);$i++){  
  5. $name=$_FILES["file"]["name"][$i];  
  6. move_uploaded_file($_FILES["file"]["tmp_name"][$i],iconv("UTF-8","gb2312",$name));  
  7. }  
  8.   
  9. ?>  

0 0
原创粉丝点击