这里使用的是bootstract的一个插件来实现
详情请查看文档中的进度条 https://v3.bootcss.com/components/
引入必要的文件
<link href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/js/bootstrap.min.js"></script>
页面结构
<input type="file" id="Pic">
<div style=" 600px;">
<div class="progress">
<div class="progress-bar progress-bar-striped active" role="progressbar"
aria-valuemin="0" aria-valuemax="100" style=" 45%">
<span class="sr-only">45% Complete</span>
</div>
</div>
</div>
js代码
注意其中onprogress事件需要卸载send之上,否则不会响应
let pic = document.getElementById('Pic');
pic.onchange = function () {
let fd = new FormData();
let long = document.querySelector('.progress-bar')
fd.append('pic', this.files[0]);
let xhr = new XMLHttpRequest();
xhr.open('post', 'http://127.0.0.1:8080/uploadHeadImg');
xhr.upload.onprogress = function(e){
long.style.width = e.loaded/e.total*100+'%'
console.log(e.loaded/e.total*100+'%')
}
xhr.send(fd);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
let response = xhr.responseText
if (xhr.getResponseHeader('Content-Type').indexOf('json') !== -1) {
response = JSON.parse(xhr.responseText)
}
}
}
}