東西很簡單,主要用到commons-fileupload,其中有一個progressListener的接口,該接口可以實現(xiàn)實時更新已上傳文件的大小,有了這個還說什么呢?
這里給出代碼:
package lc.progress;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import lc.progress.vo.fileUploadStatus;
import org.apache.commons.fileupload.ProgressListener;
public class myProgressListener implements ProgressListener {
private HttpSession session;
public myProgressListener(HttpServletRequest req) {
session=req.getSession();
fileUploadStatus status = new fileUploadStatus();
session.setAttribute("status", status);
}
/* pBytesRead 到目前為止讀取文件的比特數(shù)
* pContentLength 文件總大小
* pItems 目前正在讀取第幾個文件
* 只要在session中實時保存文件上傳的狀態(tài)(這里我用fileUploadStatus類來封裝)
*/
public void update(long pBytesRead, long pContentLength, int pItems) {
// TODO Auto-generated method stub
fileUploadStatus status = (fileUploadStatus) session.getAttribute("status");
status.setPBytesRead(pBytesRead);
status.setPContentLength(pContentLength);
status.setPItems(pItems);
}
}
然后在上傳得servlet或action中加入這樣一段代碼,就可以把自定義的progressListener添加進(jìn)去
myProgressListener getBarListener = new myProgressListener(req);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setProgressListener(getBarListener);
最后就是通過js來不斷的訪問另一個servlet來實時返回上傳狀態(tài)就可以了,限于篇幅我就不再貼代碼了,有興趣的讀者可以自己下載來看。
此外,這個代碼也可以參考一下:
public static void main(String[] args) throws Exception {
System.out.print("Progress:");
for (int i = 1; i <= 100; i++) {
System.out.print(i + "%");
Thread.sleep(100);
for (int j = 0; j <= String.valueOf(i).length(); j++) {
System.out.print("\b");
}
}
System.out.println();
}
申請創(chuàng)業(yè)報道,分享創(chuàng)業(yè)好點(diǎn)子。點(diǎn)擊此處,共同探討創(chuàng)業(yè)新機(jī)遇!