JavaWeb项目实现文件上传动态显示进度


引用:

 很久没有更新博客了,这段时间实在的忙的不可开交,项目马上就要上线了,要修补的东西太多了。当我在学习JavaWeb文件上传的时候,我就一直有一个疑问,网站上那些博客的图片是怎么上传的,因为当提交了表单之后网页就跳转了。后来我学习到了Ajax,我知道了浏览器可以异步的发送响应,这时我又有新的疑问,那就是在我上传一些文件的时候,那些网站的上传进度是怎么做到的,因为servlet直到上传完成之后才完成响应。

  最近我们的项目中有一个地方中需要用到一个功能,当用户点击一个处理按钮时,前台会实时的显示后台处理动态,由于servlet一次只能接受一个请求,而且在servlet的生命周期结束时才会把响应数据发送到前台(这一点大家可以做个这样的测试:

1 response.getWriter().print("hello");
2 Thread.sleep(10000);
3 response.getWriter().print("world");

,你们会发现前台在等待了约10s后收到了"helloworld")。所以我想到了一个方法:使用单例保存实时信息。具体的实现方法就是,当用户点击了处理按钮时,在后台开启一个线程进行处理,并且每进行到一步,就向单例中写入当前状态信息。然后编写一个servlet,用于返回单例中的信息,前台循环发送请求,这样就能实现实时显示进度的效果。

  好了,啰嗦了这么多,下面进入正题,如何实现上传文件动态显示进度,其实思想和上面的功能是一致的,我将这个功能分为三个点:

  1. 单例:用于保存进度信息;
  2. 上传servlet:用于上传文件并实时写入进度;
  3. 进度servlet:用于读取实时进度信息;

  上代码,前台:

 1 
 2 
 3 
 4 
 5 Insert title here
 6 
11 
12 
13     

File upload demo

14
15
16 17
18
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 70

  后台,单例:

 1 import java.util.Hashtable;
 2 
 3 public class ProgressSingleton {
 4     //为了防止多用户并发,使用线程安全的Hashtable
 5     private static Hashtable 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:

 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 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:

 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 }

  效果图:https://stackoverflow.com/questions/42164380/asp-net-core-file-upload-progress-session

引用网址:

ASP.Net Core File Upload Progress Session

Ask Question Asked 5 years ago Active 5 years ago Viewed 7k times  

I'm writing a file upload in ASP.Net Core and I'm trying to update a progress bar but when the Progress action is called from javascript, the session value isn't updated properly.

The progress is saved in the user Session using:

public static void StoreInt(ISession session, string key, int value)
{
    session.SetInt32(key, value);
}

The upload:

$.ajax(
  {
      url: "/Upload",
      data: formData,
      processData: false,
      contentType: false,
      type: "POST",
      success: function (data) {
          clearInterval(intervalId);
          $("#progress").hide();
          $("#upload-status").show();
      }
  }
);

Getting the progress value:

intervalId = setInterval(
  function () {
      $.post(
        "/Upload/Progress",
        function (progress) {
            $(".progress-bar").css("width", progress + "%").attr("aria-valuenow", progress);
            $(".progress-bar").html(progress + "%");
        }
      );
  },
  1000
);

Upload Action:

[HttpPost]
public async Task Index(IList files)
{
    SetProgress(HttpContext.Session, 0);
    [...]

    foreach (IFormFile file in files)
    {
        [...]
        int progress = (int)((float)totalReadBytes / (float)totalBytes * 100.0);
        SetProgress(HttpContext.Session, progress);
        // GetProgress(HttpContext.Session) returns the correct value
    }

    return Content("success");
}

Progress Action:

[HttpPost]
public ActionResult Progress()
{
    int progress = GetProgress(HttpContext.Session);
    // GetProgress doesn't return the correct value: 0 when uploading the first file, a random value (0-100) when uploading any other file

    return Content(progress.ToString());
}
c#jqueryasp.net-core se-share-sheet#willShow s-popover:shown->se-share-sheet#didShow">Share Improve this question   asked Feb 10, 2017 at 16:38 Wakam Fx 30733 silver badges1212 bronze badges
  •   Do you test this in local and what is the length of file you upload?  – Farzin Kanzi  Feb 10, 2017 at 17:10
  •   I tried in local and on a remote server, both failed. I also tried with single/multiple small/big file(s). Here I created a solution to reproduce the issue: github.com/Fxbouffant/FileUploadCore The progress action always returns 0 while the file is still being uploaded. Then it returns 100 when the file is uploaded, no value between.  – Wakam Fx  Feb 13, 2017 at 15:13 
  • 1 The interval for check the progress is 1 second. Isn't it possible download ended before it check for the process?  – Farzin Kanzi  Feb 13, 2017 at 15:17
  • 3 It is not a good approach for upload progress. and it will not be smooth progressing. I do this by xmlHttpRequest that creates a live connection, But it is asp.net not mvc. Do you want that?  – Farzin Kanzi  Feb 13, 2017 at 15:20
  •   Thank you, that's perfect. I used the xhr event to update the progression.  – Wakam Fx  Feb 13, 2017 at 16:04
Add a comment se-share-sheet#willShow s-popover:shown->se-share-sheet#didShow">Share Improve this answer

相关