在XMLHttpRequest
的open
之前重写XMLHttpRequestUpload
对象的进度事件progress
方法,监听progress
方法,计算进度,从而设置进度条。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
<style>
.progress {
width: 1000px;
height: 20px;
border: 1px solid #000;
margin: 10px;
}
.progress > div {
width: 0px;
height: 100%;
background-color: red;
}
</style>
</head>
<body>
<input type="file" id="file">
<div class="progress">
<div></div>
</div>
<button onclick="ajaxUpload()">上传</button>
<script src="jquery-3.3.1.js"></script>
<script>
function ajaxUpload() {
var file = $('#file').get(0).files[0];
var formdata = new FormData();
formdata.append('file', file);
$.ajax({
url: 'aaa.php',
type: 'post',
dataType: 'json',
data: formdata,
processData: false, //必须设置
contentType: false, //必须设置
xhr: () => {
var xhr = new XMLHttpRequest();
//console.log(xhr);
xhr.upload.onprogress = (e) => {
console.log(e);
var progressWidth = (e.loaded / e.total) * 100 + '%';
$('.progress > div').css('width', progressWidth);
}
return xhr;
}
})
}
</script>
</body>
</html>
效果如下: