<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<title></title>
<style>
#bar-warp {
width: 500px;
height: 30px;
border: 1px solid green;
}

#bar {
width: 0px;
height: 30px;
background: green;
}
</style>
</head>

<body>
<input type="file" name="pic" onchange="upfile();" />
<div id="bar-warp">
<div id="bar"></div>
</div><span id="precent"></span><br />

<script type="text/javascript">
function upfile() {
var pic = document.getElementsByTagName('input')[0].files[0];
var fd = new FormData();//利用FormData传参
var xhr = new XMLHttpRequest();
//xhr.setRequestHeader('token',sessionStorage.getItem('token'))加token
xhr.open('post', '01.php', true);
xhr.onreadystatechange = function () {
//readystate为4表示请求已完成并就绪
if (this.readyState == 4) {
document.getElementById('precent').innerHTML = this.responseText;
//在进度条下方插入百分比
}
}

xhr.upload.onprogress = function (ev) {
//如果ev.lengthComputable为true就可以开始计算上传进度
//上传进度 = 100* ev.loaded/ev.total
if (ev.lengthComputable) {
var precent = 100 * ev.loaded / ev.total;
console.log(precent);
//更改进度条,及百分比
document.getElementById('bar').style.width = precent + '%';
document.getElementById('precent').innerHTML = Math.floor(precent) + '%';
}
}
fd.append('pic', pic);//FormData传参

xhr.send(fd);

}
</script>
</body>