多文件ajax 上传

html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8"/>
<title>xhr2</title>
</head>
<body>
<div style="text-align:center;margin:100px">
<input type="file" id="file" name="file" multiple="multiple">
<button onclick="xhr2()">文件上传</button>
</div>
<script>
function xhr2(){
var xhr = new XMLHttpRequest();//第一步
//定义表单变量
var file = document.getElementById('file').files;
alert(file)
console.log(file);
//新建一个FormData对象
var formData = new FormData(); //++++++++++
//追加文件数据
for(i=0;i<file.length;i++){
formData.append("file["+i+"]", file[i]); //++++++++++
}
//formData.append("file", file[0]); //++++++++++
//post方式
xhr.open('POST', 'http://www.web.com/work/vchangyi/demo1.php'); //第二步骤
//发送请求
xhr.send(formData); //第三步骤
//ajax返回
xhr.onreadystatechange = function(){ //第四步
if ( xhr.readyState == 4 && xhr.status == 200 ) {
console.log( xhr.responseText );
alert("上传成功")
}
};
//设置超时时间
xhr.timeout = 100000;
xhr.ontimeout = function(event){
alert('请求超时!');
}
}
</script>
</body>
</html>


php
<?php
print_r($_FILES["file"]);

for($i=0;$i<count($_FILES["file"]['name']);$i++){
$name=$_FILES["file"]["name"][$i];
move_uploaded_file($_FILES["file"]["tmp_name"][$i],iconv("UTF-8","gb2312",$name));
}

?>



posted @ 2017-05-25 23:10  太空刘  阅读(1016)  评论(0编辑  收藏  举报