监听文件上传的进度 见代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
body{
background:#ccc;
}
h1,h2,h3,h4,h5,h6{
text-align: center;
}
form{
width: 400px;
margin:50px auto;
padding:20px;
border: 1px solid #eee;
border-radius: 10px;
background:#fff;
}
input[type='text'],
input[type='select'],
input[type='password'],
input[type='submit'],
input[type='password'],
input[type='button'],
input[type='file'],
select{
width: 100%;
display: block;
height: 24px;
margin-bottom:15px;
border-radius: 3px;
border:1px solid #aaa;
}
input[type='submit']{
height: 40px;
background:rgb(209, 92, 92);
border:none;
color:#fff;
font-size: 24px;;
}
input[type='radio'],
input[type='checkbox']{
height: 20px;
width:20px;
/* display: inline; */
margin:10px;
}
input[type='file']{
border:none;
}
.progress{
width: 800px;
height: 30px;
border:1px solid green;
margin:0 auto;
overflow:hidden;
position: relative;
}
.in{
width: 3%;
height: 100%;
background: red;
}
span{
position: absolute;
left:390px;
top:0;
}
</style>
</head>
<body>
<form id="from1">
用户名:<input type="text" name="username">
密码: <input type="password" name="password">
头像: <input type="file" name="myfile" id="pic">
用户名:<input type="button" name="发送ajax请求" id="sub">
</form>
<div class="progress">
<div class="in"></div>
<span>0%</span>
</div>
<img src="" alt="">
<script>
document.querySelector("#sub").onclick =function(){
var xhr = new XMLHttpRequest();
xhr.open("post",'uploadFile.php');
var myform=document.querySelector("#form1");
var fromData= new FormData(myfrom);
// 监听文件上传的进度:这个监听必须在send之前设置
xhr.upload.onprogress = function(e){
var current = e.loaded;
var total = e.total;
var percent=current/total*100+'%';
document.querySelector(".in").style.width=person;
document.querySelector("span").innerHTML = Math.floor(current/total*100)+"%";
}
xhr.send(formData);
xhr.onreadystatechange=function(){
if(xhr.status=200&&xhr.readyState==4){
console.log(xhr.responseText);
}
}
}
</script>
</body>
</html>
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。