<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>上传文件TEST</title>
<style>
.demo{ width:50%; margin:120px auto;}
</style>
</head>
<body>
<div class="demo">
<!--添加滚动条标签,html5新增-->
<progress max="100" value="0"></progress>
<!--表示类型为文件上传,multiple(html5新增加)表示多个文件,默认单个-->
<input type="file" class="tempFile" multiple="multiple"/>
<button onClick="ajaxSubmit()">提交</button>
</div>
<script>
function ajaxSubmit(){
var files =document.querySelector('.tempFile').files;
//因为不确定有多少个文件,所以我们使用循环遍历的方式将文件都传递给FormData
var formdata =new FormData();
for(var i=0;i<files.length;i++){
var file = files[i];
formdata.append('myflie'+i,file);
}
//发送ajax请求
var xhr =new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
if(xhr.status==200){
console.log(xhr.responseText);
}
}
}
//获得进度条
var progressBar = document.querySelector("progress");
//上传回调的进度回调,上传进度只有有变化,本函数就会自动执行
xhr.upload.onprogress =function(eve){
//eve.lengthComputable
//表示文件是否已经上传100%,默认是true,表示没有100%
//上传100%后变成false
if(eve.lengthComputable){
//eve.loaded 表示已经上传的
//eve.total 表示总数
progressBar.value =(eve.loaded/eve.total)*100;
}
}
//准备发送
xhr.open('post','receive.php',true);
xhr.send(formdata);
}
</script>
</body>
</html>