java實現下載時進度條提示
阿新 • • 發佈:2018-12-07
1、實現原理
計算出已經處理的資料記錄數與所有需要匯出的資料記錄數的比例,根據每一個登陸使用者的不同將比例存入快取中,前臺設計一個定時器,每隔一段時間去快取中獲取比例,然後根據比例來展示一下下載的進度。
2、具體程式碼實現
//下載比例的儲存 long totalCount = 總記錄數; long a = i * 100 / totalCount; cacheService.setCache(當前登陸使用者ID+"特定的標誌", a+""); -------------------------------------------------------------------------------- //下載比例的獲取 String cache = cacheService.getCache(當前登陸使用者ID+"特定的標誌"); if (cache == null) { cache = "0"; } result.put("info", cache); if("f".equals(cache)) { cacheService.setCache(session("F_UID")+"PROGRESS","0"); }
$("#export").click(function(){ //通過ajax去下載 $.ajax({ }); //顯示進度條 $("#myProgress").show(); $("#myBarMsg").show(); $("#myBarMsg").html("當前進度:0%"); var elem = document.getElementById("myBar"); var width = 0; //啟動定時器 var progressFunction = setInterval(progress, 1000); //定時器執行任務 function progress(){ $.ajax({ type:"post", url:"", //獲取快取中下載進度的url data:{ }, success:function(data){ if(data.info == 'f'){ width = 100; elem.style.width = width + '%'; $("#myBarMsg").html("當前進度:100%,匯出成功!"); clearInterval(progressFunction); setTimeout(function(){ $("#myProgress").hide(); $("#myBarMsg").hide(); width = 0; elem.style.width = width + '%'; }, 5000); }else{ console.log("已經處理的資料條數:"+data.info); width = data.info; elem.style.width = width + '%'; $("#myBarMsg").html("當前進度:"+data.info+"%"+" (<label style='color:red;'>匯出過程中請不要切換目錄,可開啟新的視窗檢視其他!</label>)"); } }, error:function(xmlHttpReq, textStatus, errorThrown){ alert("匯出失敗,失敗原因:" + textStatus+","+errorThrown); } }); } });
<!-- css --> #myProgress { width: 100%; height: 30px; position: relative; background-color: #ddd; border-radius:5px; } #myBar { background-color: #4CAF50; width: 0px; height: 30px; position: absolute; border-radius:5px; } <!-- 下載進度 --> <div id="myProgress" style="display:none;"> <div id="myBar"></div> </div> <div id="myBarMsg" z-index:100></div>