Ajax⽂件上传进度监听之progress案例详解$.ajax实现
<!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>
<script src="./libs/jquery/jquery.js"></script>
<style>
div {
width: 0%;
height: 20px;
background-color: #f00;
/* transition: all 0.2s; */
}
</style>
</head>
<body>
<div></div>
<input type="file" />
<script>
$(function() {
// ⽤户选择好⽂件之后单击弹出层的“打开”按钮的触发事件是:change
$('input').on('change', function() {
// 1.收集⽂件数据
let myfile = $('input')[0].files[0]
let formdata = new FormData()
formdata.append('file_data', myfile)
// 2.发起ajax请求
$.ajax({
url: '127.0.0.1:3001/uploadFile',
type: 'post',
data: formdata,
processData: false,
contentType: false,
xhr: function() {
let newxhr = new XMLHttpRequest()
// 添加⽂件上传的监听
// onprogress:进度监听事件,只要上传⽂件的进度发⽣了变化,就会⾃动的触发这个事件
progress = function(e) {
console.log(e)
let percent = (e.loaded / e.total) * 100 + '%'
$('div').css('width', percent)
}
return newxhr
},
success: function(res) {
console.log(res)
},
dataType: 'json'
})
})
})
</script>
</body>
</html>
原⽣实现:
<!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>
<script src="./libs/jquery/jquery.js"></script>
<style>
div {
width: 0%;
height: 20px;
background-color: #f00;
/* transition: all 0.2s; */
}
</style>
</head>
<body>ajax实例 文件浏览
<div></div>
<input type="file" />
<script>
$(function() {
// ⽤户选择好⽂件之后单击弹出层的“打开”按钮的触发事件是:change
$('input').on('change', function() {
// 1.收集⽂件数据
let myfile = $('input')[0].files[0]
let formdata = new FormData()
formdata.append('file_data', myfile)
let xhr = new XMLHttpRequest()
xhr.open('post', '127.0.0.1:3001/uploadFile')
/
/ 细节1:⽂件上传,如果使⽤fromdata,则不要设置请求头
progress = function(e) {
console.log(e)
let percent = (e.loaded / e.total) * 100 + '%'
$('div').css('width', percent)
}
// 细节2:send中可以直接传递formdata
xhr.send(formdata)
})
})
</script>
</body>
</html>
到此这篇关于Ajax ⽂件上传进度监听之progress案例详解的⽂章就介绍到这了,更多相关Ajax ⽂件上传进度监听之progress内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。