這裡關於servlet如何上傳檔案就先不說了,將如何得到已經上傳的檔案資料的百分比...
首先我們先寫一個類這個類要實現ProgressListener這個介面,實現裡面的update(...)方法.代碼如下
package com.test.servlet;import java.text.DecimalFormat;import javax.servlet.http.HttpServletRequest;import org.apache.commons.fileupload.ProgressListener;public class UploadProgressListener implements ProgressListener{private HttpServletRequest request = null ;private DecimalFormat decimalFormat = new DecimalFormat("#00.0");public UploadProgressListener(HttpServletRequest request){this.request = request;}public void update(long pBytesRead, long pContentLength, int pItems){ double percent= (double)pBytesRead*100/(double)pContentLength; String hadDownloadPercent = decimalFormat.format(percent).toString();request.getSession().setAttribute("hadDownloadPercent",hadDownloadPercent) ;}}
這個類寫完之後,我們再寫一個servlet,這個servlet用於被Ajax在短暫的時間內不斷請求資料,比如請求間隔是100ms
上代碼
package com.test.servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;public class ReadProgressInSessionServlet extends HttpServlet{public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{HttpSession session = request.getSession();String hadDownloadPercent = (String)session.getAttribute("hadDownloadPercent");response.setCharacterEncoding("utf-8");PrintWriter printWriter = response.getWriter();printWriter.write(hadDownloadPercent);printWriter.flush();}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{this.doGet(request,response);}}
還有一個就是上傳檔案的核心類
ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);servletFileUpload.setProgressListener(new UploadProgressListener(req));
其中req是HttpServletRequest對象 UploadProgressListener是ProgressListener介面的實作類別...
最後就是通過JavaScript頻繁的發起http請求,也就是Ajax...不過這種方式可能對伺服器效能造成影響...
function f(){var demonstrateHadUploadFileSizeArea = document.getElementById("demonstrateHadUploadFileSizeArea");var idiv=document.getElementById('hadUploadPercent');var ibox=document.getElementById('demonstrateArea');var url = "ReadProgressInSessionServlet" ;//alert(url);var xmlHttpRequest = null ;if(window.ActiveXObject){xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP"); }else if(window.XMLHttpRequest){xmlHttpRequest = new XMLHttpRequest();}if(null != xmlHttpRequest){xmlHttpRequest.open("GET", url.toString(), true);xmlHttpRequest.onreadystatechange = ajaxCallBack;xmlHttpRequest.send(null);}function ajaxCallBack(){if(xmlHttpRequest.readyState == 4){if(xmlHttpRequest.status == 200){var responseText = xmlHttpRequest.responseText;//demonstrateHadUploadFileSizeArea.innerHTML = responseText;var iWidth = responseText;idiv.style.width=idiv.offsetWidth+1+'px';idiv.innerHTML= Math.round(iWidth)+"%";}}}}function g(){setInterval("f()",5);}