話很少說 直接上代碼javascript
$.ajax({ url: 'URL', type: 'POST', data: fd, processData: false, //用來回避jquery對formdata的默認序列化,XMLHttpRequest會對其進行正確處理 contentType: false, //設爲false纔會得到正確的conten-Type xhr: function() { //用以顯示上傳進度 var xhr = $.ajaxSettings.xhr(); if (xhr.upload) { xhr.upload.addEventListener('progress', function(event) { var percent = Math.floor(event.loaded / event.total * 100); document.querySelector("#progress .progress-item").style.width = percent + "%"; }, false); } return xhr }, success: function(data) { } })
var xhr = new XMLHttpRequest(); xhr.open('POST', 'url'); // 上傳完成後的回調函數 xhr.onreadystatechange = function() { if (xhr.status === 200) { console.log(xhr.responseText); } else { console.log('上傳出錯'); } }; // 獲取上傳進度 xhr.upload.onprogress = function(event) { console.log(event.loaded) console.log(event.total) if (event.lengthComputable) { var percent = Math.floor(event.loaded / event.total * 100); document.querySelector("#progress .progress-item").style.width = percent + "%"; // 設置進度顯示 console.log(percent) } }; xhr.send(fd);
html 和相關進度條csscss
<div id="progress"> <div class="progress-item"></div> </div>
#progress { height: 10px; width: 300px; border: 1px solid gold; position: relative; border-radius: 5px; } #progress .progress-item { height: 100%; position: absolute; left: 0; top: 0; background: chartreuse; border-radius: 5px; transition: width .3s linear; }
有任何問題 下方留言html