當前位置:首頁 >  站長 >  編程技術 >  正文

Java如何實現(xiàn)動態(tài)顯示文件上傳進度條

 2021-01-07 16:37  來源: 網(wǎng)絡綜合   我來投稿 撤稿糾錯

  阿里云優(yōu)惠券 先領券再下單

本文實例實現(xiàn)文件上傳的進度顯示,我們先看看都有哪些問題我們要解決。

1 上傳數(shù)據(jù)的處理進度跟蹤

2 進度數(shù)據(jù)在用戶頁面的顯示

就這么2個問題,

第一個問題,主要是組件的選擇

必須支持數(shù)據(jù)處理偵聽或通知的組件。當然,我肯定只用我自己的組件啦?;驹硎?/p>

1 使用request.getContentLength() 讀取到處理數(shù)據(jù)的總長度,注意這個長度不等于文件的長度,因為Base64等編碼會增加數(shù)據(jù)量,如果超過了允許的長度,直接返回-1;

2 在每讀取一部分數(shù)據(jù)時(比如一行,或者64K,或者你自定義的字節(jié)數(shù)),將讀取的字節(jié)數(shù)通知我們的進度跟蹤程序。我取名為 UploadListener代碼如下

/*
* 處理附件上傳的通知。

* 各位可以繼承這個類,來實現(xiàn)自己的特殊處理。
*
* @author 趙學慶 www.java2000.net
*/
 public class UploadListener ... {
 // 調試模式將在控制臺打印出一些數(shù)據(jù)
 private boolean debug;

 // 總數(shù)據(jù)字節(jié)數(shù)
 private int total;

 // 當前已經(jīng)處理的數(shù)據(jù)字節(jié)數(shù)
 private int totalCurrent = 0 ;

 // 延遲,用來調試用,免得速度太快,根本卡看不到進度
 private int delay = 0 ;

 /** */ /**
 * 處理數(shù)據(jù)通知的方法。

 * 保存已經(jīng)處理的數(shù)據(jù)。并且在一定的比例進行延遲。默認每1%

 * 如果不需用延遲,可以刪掉內部的代碼,加快速度。
 *
 * @param size 增加的字節(jié)數(shù)
 */
 public void increaseTotalCurrent( long size) ... {
 this .totalCurrent += size;
 try ... {
 currentRate = totalCurrent * 100 / total;
  if (currentRate > lastRate) ... {
  if (delay > 0 ) ... {
  Thread.sleep(delay);
  }
  if (debug) ... {
  System.out.println( " rate= " + totalCurrent + " / " + total + " / " + (totalCurrent * 100 / total));
  }
  lastRate = currentRate;
 }
 } catch (Exception e) ... {
 e.printStackTrace();
 }
 }

 /** */ /**
 * 讀取全部自己數(shù)
 *
 * @return
 */
 public int getTotal() ... {
 return total;
 }

 /** */ /**
 * 讀取已經(jīng)處理的字節(jié)數(shù)
 *
 * @return
 */
 public int getTotalCurrent() ... {
 return totalCurrent;
 }

 private long lastRate = 0 ;

 private long currentRate = 0 ;

 public int getDelay() ... {
 return delay;
 }

 public void setDelay( int delay) ... {
 this .delay = delay;
 }

 public void setTotal( int total) ... {
 this .total = total;
 }

 public boolean isDebug() ... {
 return debug;
 }

 public void setDebug( boolean debug) ... {
 this .debug = debug;
 }
}
你學會了嗎?

申請創(chuàng)業(yè)報道,分享創(chuàng)業(yè)好點子。點擊此處,共同探討創(chuàng)業(yè)新機遇!

相關標簽
java進度條

相關文章

熱門排行

信息推薦