好久沒有更新博客了,這段時間實在的忙的不可開交,項目立刻就要上線了,要修補的東西太多了。當我在學習JavaWeb文件上傳的時候,我就一直有一個疑問,網站上那些博客的圖片是怎麼上傳的,由於當提交了表單以後網頁就跳轉了。後來我學習到了Ajax,我知道了瀏覽器能夠異步的發送響應,這時我又有新的疑問,那就是在我上傳一些文件的時候,那些網站的上傳進度是怎麼作到的,由於servlet直到上傳完成以後才完成響應。javascript
最近咱們的項目中有一個地方中須要用到一個功能,當用戶點擊一個處理按鈕時,前臺會實時的顯示後臺處理動態,因爲servlet一次只能接受一個請求,並且在servlet的生命週期結束時纔會把響應數據發送到前臺(這一點你們能夠作個這樣的測試:css
1 response.getWriter().print("hello"); 2 Thread.sleep(10000); 3 response.getWriter().print("world");
,大家會發現前臺在等待了約10s後收到了"helloworld")。因此我想到了一個方法:使用單例保存實時信息。具體的實現方法就是,當用戶點擊了處理按鈕時,在後臺開啓一個線程進行處理,而且每進行到一步,就向單例中寫入當前狀態信息。而後編寫一個servlet,用於返回單例中的信息,前臺循環發送請求,這樣就能實現實時顯示進度的效果。html
好了,囉嗦了這麼多,下面進入正題,如何實現上傳文件動態顯示進度,其實思想和上面的功能是一致的,我將這個功能分爲三個點:java
上代碼,前臺:jquery
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Insert title here</title> 6 <style type="text/css"> 7 #progress:after { 8 content: '%'; 9 } 10 </style> 11 </head> 12 <body> 13 <h3>File upload demo</h3> 14 <form action="TestServlet" method="post" enctype="multipart/form-data" id="dataForm"> 15 <input type="file" name="file" id="fileInput"> <br> 16 <input type="submit" value="submit" id="submit"> 17 </form> 18 <div id="progress"></div> 19 <script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script> 20 <script type="text/javascript"> 21 (function () { 22 var form = document.getElementById("dataForm"); 23 var progress = document.getElementById("progress"); 24 25 $("#submit").click(function(event) { 26 //阻止默認事件 27 event.preventDefault(); 28 //循環查看狀態 29 var t = setInterval(function(){ 30 $.ajax({ 31 url: 'ProgressServlet', 32 type: 'POST', 33 dataType: 'text', 34 data: { 35 filename: fileInput.files[0].name, 36 }, 37 success: function (responseText) { 38 var data = JSON.parse(responseText); 39 //前臺更新進度 40 progress.innerText = parseInt((data.progress / data.size) * 100); 41 }, 42 error: function(){ 43 console.log("error"); 44 } 45 }); 46 }, 500); 47 //上傳文件 48 $.ajax({ 49 url: 'UploadServlet', 50 type: 'POST', 51 dataType: 'text', 52 data: new FormData(form), 53 processData: false, 54 contentType: false, 55 success: function (responseText) { 56 //上傳完成,清除循環事件 57 clearInterval(t); 58 //將進度更新至100% 59 progress.innerText = 100; 60 }, 61 error: function(){ 62 console.log("error"); 63 } 64 }); 65 return false; 66 }); 67 })(); 68 </script> 69 </body> 70 </html>
後臺,單例:ajax
1 import java.util.Hashtable; 2 3 public class ProgressSingleton { 4 //爲了防止多用戶併發,使用線程安全的Hashtable 5 private static Hashtable<Object, Object> table = new Hashtable<>(); 6 7 public static void put(Object key, Object value){ 8 table.put(key, value); 9 } 10 11 public static Object get(Object key){ 12 return table.get(key); 13 } 14 15 public static Object remove(Object key){ 16 return table.remove(key); 17 } 18 }
上傳servlet:apache
1 import java.io.File; 2 import java.io.FileOutputStream; 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.util.List; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.annotation.WebServlet; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 13 import org.apache.tomcat.util.http.fileupload.FileItem; 14 import org.apache.tomcat.util.http.fileupload.FileUploadException; 15 import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory; 16 import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload; 17 import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext; 18 19 import singleton.ProgressSingleton; 20 21 @WebServlet("/UploadServlet") 22 public class UploadServlet extends HttpServlet { 23 private static final long serialVersionUID = 1L; 24 25 public UploadServlet() { 26 } 27 28 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 29 30 DiskFileItemFactory factory = new DiskFileItemFactory(); 31 factory.setSizeThreshold(4*1024); 32 33 ServletFileUpload upload = new ServletFileUpload(factory); 34 35 List<FileItem> fileItems; 36 try { 37 fileItems = upload.parseRequest(new ServletRequestContext(request)); 38 //獲取文件域 39 FileItem fileItem = fileItems.get(0); 40 //使用sessionid + 文件名生成文件號 41 String id = request.getSession().getId() + fileItem.getName(); 42 //向單例哈希表寫入文件長度和初始進度 43 ProgressSingleton.put(id + "Size", fileItem.getSize()); 44 //文件進度長度 45 long progress = 0; 46 //用流的方式讀取文件,以即可以實時的獲取進度 47 InputStream in = fileItem.getInputStream(); 48 File file = new File("D:/test"); 49 file.createNewFile(); 50 FileOutputStream out = new FileOutputStream(file); 51 byte[] buffer = new byte[1024]; 52 int readNumber = 0; 53 while((readNumber = in.read(buffer)) != -1){ 54 //每讀取一次,更新一次進度大小 55 progress = progress + readNumber; 56 //向單例哈希表寫入進度 57 ProgressSingleton.put(id + "Progress", progress); 58 out.write(buffer); 59 } 60 //當文件上傳完成以後,從單例中移除這次上傳的狀態信息 61 ProgressSingleton.remove(id + "Size"); 62 ProgressSingleton.remove(id + "Progress"); 63 in.close(); 64 out.close(); 65 } catch (FileUploadException e) { 66 e.printStackTrace(); 67 } 68 69 response.getWriter().print("done"); 70 } 71 72 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 73 doGet(request, response); 74 } 75 76 }
進度servlet:json
1 import java.io.IOException; 2 3 import javax.servlet.ServletException; 4 import javax.servlet.annotation.WebServlet; 5 import javax.servlet.http.HttpServlet; 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 9 import net.sf.json.JSONObject; 10 import singleton.ProgressSingleton; 11 12 @WebServlet("/ProgressServlet") 13 public class ProgressServlet extends HttpServlet { 14 private static final long serialVersionUID = 1L; 15 16 public ProgressServlet() { 17 super(); 18 // TODO Auto-generated constructor stub 19 } 20 21 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 22 23 String id = request.getSession().getId(); 24 String filename = request.getParameter("filename"); 25 //使用sessionid + 文件名生成文件號,與上傳的文件保持一致 26 id = id + filename; 27 Object size = ProgressSingleton.get(id + "Size"); 28 size = size == null ? 100 : size; 29 Object progress = ProgressSingleton.get(id + "Progress"); 30 progress = progress == null ? 0 : progress; 31 JSONObject json = new JSONObject(); 32 json.put("size", size); 33 json.put("progress", progress); 34 response.getWriter().print(json.toString()); 35 } 36 37 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 38 doGet(request, response); 39 } 40 41 }
效果圖:瀏覽器