Ajax 文件上傳進度監(jiān)聽之upload.onprogress案例詳解
更新時間:2021年09月09日 10:46:21 作者:Henry_ww
這篇文章主要介紹了Ajax 文件上傳進度監(jiān)聽之upload.onprogress案例詳解,本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下
$.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() {
// 用戶選擇好文件之后單擊彈出層的“打開”按鈕的觸發(fā)事件是:change
$('input').on('change', function() {
// 1.收集文件數據
let myfile = $('input')[0].files[0]
let formdata = new FormData()
formdata.append('file_data', myfile)
// 2.發(fā)起ajax請求
$.ajax({
url: 'http://127.0.0.1:3001/uploadFile',
type: 'post',
data: formdata,
processData: false,
contentType: false,
xhr: function() {
let newxhr = new XMLHttpRequest()
// 添加文件上傳的監(jiān)聽
// onprogress:進度監(jiān)聽事件,只要上傳文件的進度發(fā)生了變化,就會自動的觸發(fā)這個事件
newxhr.upload.onprogress = 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>
<div></div>
<input type="file" />
<script>
$(function() {
// 用戶選擇好文件之后單擊彈出層的“打開”按鈕的觸發(fā)事件是: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', 'http://127.0.0.1:3001/uploadFile')
// 細節(jié)1:文件上傳,如果使用fromdata,則不要設置請求頭
xhr.upload.onprogress = function(e) {
console.log(e)
let percent = (e.loaded / e.total) * 100 + '%'
$('div').css('width', percent)
}
// 細節(jié)2:send中可以直接傳遞formdata
xhr.send(formdata)
})
})
</script>
</body>
</html>
到此這篇關于Ajax 文件上傳進度監(jiān)聽之upload.onprogress案例詳解的文章就介紹到這了,更多相關Ajax 文件上傳進度監(jiān)聽之upload.onprogress內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
JavaScript中獲得CheckBox狀態(tài)的方法小結
在 JavaScript 中,獲取復選框(CheckBox)的狀態(tài)(選中或未選中)可以通過以下幾種方式實現,以下是具體方法及示例,并通過代碼示例介紹的非常詳細,需要的朋友可以參考下2025-03-03

