很久沒(méi)有更新博客了,這段時(shí)間實(shí)在的忙的不可開(kāi)交,項(xiàng)目馬上就要上線了,要修補(bǔ)的東西太多了。當(dāng)我在學(xué)習(xí)JavaWeb文件上傳的時(shí)候,我就一直有一個(gè)疑問(wèn),網(wǎng)站上那些博客的圖片是怎么上傳的,因?yàn)楫?dāng)提交了表單之后網(wǎng)頁(yè)就跳轉(zhuǎn)了。后來(lái)我學(xué)習(xí)到了Ajax,我知道了瀏覽器可以異步的發(fā)送響應(yīng),這時(shí)我又有新的疑問(wèn),那就是在我上傳一些文件的時(shí)候,那些網(wǎng)站的上傳進(jìn)度是怎么做到的,因?yàn)閟ervlet直到上傳完成之后才完成響應(yīng)。
10年積累的成都網(wǎng)站設(shè)計(jì)、做網(wǎng)站經(jīng)驗(yàn),可以快速應(yīng)對(duì)客戶對(duì)網(wǎng)站的新想法和需求。提供各種問(wèn)題對(duì)應(yīng)的解決方案。讓選擇我們的客戶得到更好、更有力的網(wǎng)絡(luò)服務(wù)。我雖然不認(rèn)識(shí)你,你也不認(rèn)識(shí)我。但先做網(wǎng)站設(shè)計(jì)后付款的網(wǎng)站建設(shè)流程,更有九臺(tái)免費(fèi)網(wǎng)站建設(shè)讓你可以放心的選擇與我們合作。
最近我們的項(xiàng)目中有一個(gè)地方中需要用到一個(gè)功能,當(dāng)用戶點(diǎn)擊一個(gè)處理按鈕時(shí),前臺(tái)會(huì)實(shí)時(shí)的顯示后臺(tái)處理動(dòng)態(tài),由于servlet一次只能接受一個(gè)請(qǐng)求,而且在servlet的生命周期結(jié)束時(shí)才會(huì)把響應(yīng)數(shù)據(jù)發(fā)送到前臺(tái)(這一點(diǎn)大家可以做個(gè)這樣的測(cè)試:
response.getWriter().print("hello"); Thread.sleep(10000); response.getWriter().print("world");
你們會(huì)發(fā)現(xiàn)前臺(tái)在等待了約10s后收到了"helloworld")。所以我想到了一個(gè)方法:使用單例保存實(shí)時(shí)信息。具體的實(shí)現(xiàn)方法就是,當(dāng)用戶點(diǎn)擊了處理按鈕時(shí),在后臺(tái)開(kāi)啟一個(gè)線程進(jìn)行處理,并且每進(jìn)行到一步,就向單例中寫(xiě)入當(dāng)前狀態(tài)信息。然后編寫(xiě)一個(gè)servlet,用于返回單例中的信息,前臺(tái)循環(huán)發(fā)送請(qǐng)求,這樣就能實(shí)現(xiàn)實(shí)時(shí)顯示進(jìn)度的效果。
好了,啰嗦了這么多,下面進(jìn)入正題,如何實(shí)現(xiàn)上傳文件動(dòng)態(tài)顯示進(jìn)度,其實(shí)思想和上面的功能是一致的,我將這個(gè)功能分為三個(gè)點(diǎn):
1.單例:用于保存進(jìn)度信息;
2.上傳servlet:用于上傳文件并實(shí)時(shí)寫(xiě)入進(jìn)度;
3.進(jìn)度servlet:用于讀取實(shí)時(shí)進(jìn)度信息;
上代碼,前臺(tái):
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> <style type="text/css"> #progress:after { content: '%'; } </style> </head> <body> <h4>File upload demo</h4> <form action="TestServlet" method="post" enctype="multipart/form-data" id="dataForm"> <input type="file" name="file" id="fileInput"> <br> <input type="submit" value="submit" id="submit"> </form> <div id="progress"></div> <script type="text/javascript" src="scripts/jquery-1.9.1.min.js"></script> <script type="text/javascript"> (function () { var form = document.getElementById("dataForm"); var progress = document.getElementById("progress"); $("#submit").click(function(event) { //阻止默認(rèn)事件 event.preventDefault(); //循環(huán)查看狀態(tài) var t = setInterval(function(){ $.ajax({ url: 'ProgressServlet', type: 'POST', dataType: 'text', data: { filename: fileInput.files[0].name, }, success: function (responseText) { var data = JSON.parse(responseText); //前臺(tái)更新進(jìn)度 progress.innerText = parseInt((data.progress / data.size) * 100); }, error: function(){ console.log("error"); } }); }, 500); //上傳文件 $.ajax({ url: 'UploadServlet', type: 'POST', dataType: 'text', data: new FormData(form), processData: false, contentType: false, success: function (responseText) { //上傳完成,清除循環(huán)事件 clearInterval(t); //將進(jìn)度更新至100% progress.innerText = 100; }, error: function(){ console.log("error"); } }); return false; }); })(); </script> </body> </html>
后臺(tái),單例:
import java.util.Hashtable; public class ProgressSingleton { //為了防止多用戶并發(fā),使用線程安全的Hashtable private static Hashtable<Object, Object> table = new Hashtable<>(); public static void put(Object key, Object value){ table.put(key, value); } public static Object get(Object key){ return table.get(key); } public static Object remove(Object key){ return table.remove(key); } }
上傳servlet:
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.tomcat.util.http.fileupload.FileItem; import org.apache.tomcat.util.http.fileupload.FileUploadException; import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory; import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload; import org.apache.tomcat.util.http.fileupload.servlet.ServletRequestContext; import singleton.ProgressSingleton; @WebServlet("/UploadServlet") public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; public UploadServlet() { } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(4*1024); ServletFileUpload upload = new ServletFileUpload(factory); List<FileItem> fileItems; try { fileItems = upload.parseRequest(new ServletRequestContext(request)); //獲取文件域 FileItem fileItem = fileItems.get(0); //使用sessionid + 文件名生成文件號(hào) String id = request.getSession().getId() + fileItem.getName(); //向單例哈希表寫(xiě)入文件長(zhǎng)度和初始進(jìn)度 ProgressSingleton.put(id + "Size", fileItem.getSize()); //文件進(jìn)度長(zhǎng)度 long progress = 0; //用流的方式讀取文件,以便可以實(shí)時(shí)的獲取進(jìn)度 InputStream in = fileItem.getInputStream(); File file = new File("D:/test"); file.createNewFile(); FileOutputStream out = new FileOutputStream(file); byte[] buffer = new byte[1024]; int readNumber = 0; while((readNumber = in.read(buffer)) != -1){ //每讀取一次,更新一次進(jìn)度大小 progress = progress + readNumber; //向單例哈希表寫(xiě)入進(jìn)度 ProgressSingleton.put(id + "Progress", progress); out.write(buffer); } //當(dāng)文件上傳完成之后,從單例中移除此次上傳的狀態(tài)信息 ProgressSingleton.remove(id + "Size"); ProgressSingleton.remove(id + "Progress"); in.close(); out.close(); } catch (FileUploadException e) { e.printStackTrace(); } response.getWriter().print("done"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
進(jìn)度servlet:
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import singleton.ProgressSingleton; @WebServlet("/ProgressServlet") public class ProgressServlet extends HttpServlet { private static final long serialVersionUID = 1L; public ProgressServlet() { super(); // TODO Auto-generated constructor stub } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String id = request.getSession().getId(); String filename = request.getParameter("filename"); //使用sessionid + 文件名生成文件號(hào),與上傳的文件保持一致 id = id + filename; Object size = ProgressSingleton.get(id + "Size"); size = size == null ? 100 : size; Object progress = ProgressSingleton.get(id + "Progress"); progress = progress == null ? 0 : progress; JSONObject json = new JSONObject(); json.put("size", size); json.put("progress", progress); response.getWriter().print(json.toString()); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
效果圖:
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。
文章名稱:JavaWeb項(xiàng)目實(shí)現(xiàn)文件上傳動(dòng)態(tài)顯示進(jìn)度實(shí)例
文章URL:http://www.rwnh.cn/article22/pedocc.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供軟件開(kāi)發(fā)、虛擬主機(jī)、定制網(wǎng)站、動(dòng)態(tài)網(wǎng)站、商城網(wǎng)站、外貿(mào)網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
營(yíng)銷型網(wǎng)站建設(shè)知識(shí)