南通颐猩文化传播有限公司

當(dāng)前位置:首頁(yè) >  站長(zhǎng) >  編程技術(shù) >  正文

Java如何實(shí)現(xiàn)動(dòng)態(tài)顯示文件上傳進(jìn)度條

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

  域名預(yù)訂/競(jìng)價(jià),好“米”不錯(cuò)過

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

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

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

就這么2個(gè)問題,

第一個(gè)問題,主要是組件的選擇

必須支持?jǐn)?shù)據(jù)處理偵聽或通知的組件。當(dāng)然,我肯定只用我自己的組件啦。基本原理是

1 使用request.getContentLength() 讀取到處理數(shù)據(jù)的總長(zhǎng)度,注意這個(gè)長(zhǎng)度不等于文件的長(zhǎng)度,因?yàn)锽ase64等編碼會(huì)增加數(shù)據(jù)量,如果超過了允許的長(zhǎng)度,直接返回-1;

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

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

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

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

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

 // 延遲,用來調(diào)試用,免得速度太快,根本卡看不到進(jìn)度
 private int delay = 0 ;

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

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

 * 如果不需用延遲,可以刪掉內(nèi)部的代碼,加快速度。
 *
 * @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;
 }
}
你學(xué)會(huì)了嗎?

申請(qǐng)創(chuàng)業(yè)報(bào)道,分享創(chuàng)業(yè)好點(diǎn)子。點(diǎn)擊此處,共同探討創(chuàng)業(yè)新機(jī)遇!

相關(guān)標(biāo)簽
java進(jìn)度條

相關(guān)文章

熱門排行

信息推薦