springMVC 整合进度条

springMVC 整合进度条

https://blog.csdn.net/javaer_lee/article/details/52514480

最终效果:

本文将使用   apache fileupload   ,spring MVC   jquery1.6x , bootstrap  实现一个带进度条的多文件上传,

由于fileupload 的局限,暂不能实现每个上传文件都显示进度条,只能实现一个总的进度条,效果如图,

此文我们假定你了解SPRING MVC   ,jquery   

bootstrap 可以到此下载:http://www.bootcss.com/

两个JAR包 :commons-fileupload-1.2.jar

                      commons-io-2.4.jar

1.jsp 页面

  1.  
    1. <!DOCTYPE html>
  2.  
    2. <%@ page contentType="text/html;charset=UTF-8"%>
  3.  
    3. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
  4.  
    4. <html xmlns="http://www.w3.org/1999/xhtml">
  5.  
    5. <head>
  6.  
    6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  7.  
    7. <script src="../js/jquery-1.6.4.js" type="text/javascript"></script>
  8.  
    8. <link rel="stylesheet" type="text/css" href="../css/bootstrap.css"/>
  9.  
    9. </head>
  10.  
    10. <body>
  11.  
    11. <form id='fForm' class="form-actions form-horizontal" action="../upload.html"
  12.  
    12. encType="multipart/form-data" target="uploadf" method="post">
  13.  
    13. <div class="control-group">
  14.  
    14. <label class="control-label">上传文件:</label>
  15.  
    15. <div class="controls">
  16.  
    16. <input type="file" name="file" style="550">
  17.  
    17.
  18.  
    18. </div>
  19.  
    19. <div class="controls">
  20.  
    20. <input type="file" name="file" style="550">
  21.  
    21. </div>
  22.  
    22. <div class="controls">
  23.  
    23. <input type="file" name="file" style="550">
  24.  
    24. </div>
  25.  
    25. <label class="control-label">上传进度:</label>
  26.  
    26. <div class="controls">
  27.  
    27. <div class="progress progress-success progress-striped" style="50%">
  28.  
    28. <div id = 'proBar' class="bar" style=" 0%"></div>
  29.  
    29. </div>
  30.  
    30. </div>
  31.  
    31. </div>
  32.  
    32.
  33.  
    33. <div class="control-group">
  34.  
    34. <div class="controls">
  35.  
    35. <button type="button" id="subbut" class="btn">submit</button>
  36.  
    36. </div>
  37.  
    37. </div>
  38.  
    38. </form>
  39.  
    39. <iframe name="uploadf" style="display:none"></iframe>
  40.  
    40. </body>
  41.  
    41. </html>
  42.  
    42. <script >
  43.  
    43. $(document).ready(function(){
  44.  
    44. $('#subbut').bind('click',
  45.  
    45. function(){
  46.  
    46. $('#fForm').submit();
  47.  
    47. var eventFun = function(){
  48.  
    48. $.ajax({
  49.  
    49. type: 'GET',
  50.  
    50. url: '../process.json',
  51.  
    51. data: {},
  52.  
    52. dataType: 'json',
  53.  
    53. success : function(data){
  54.  
    54. $('#proBar').css('width',data.rate+''+'%');
  55.  
    55. $('#proBar').empty();
  56.  
    56. $('#proBar').append(data.show);
  57.  
    57. if(data.rate == 100){
  58.  
    58. window.clearInterval(intId);
  59.  
    59. }
  60.  
    60. }});};
  61.  
    61. var intId = window.setInterval(eventFun,500);
  62.  
    62. });
  63.  
    63. });
  64.  
    64. </script>

  2.java 代码
  1.  
    import java.util.List;
  2.  
    import javax.servlet.http.HttpServletRequest;
  3.  
    import javax.servlet.http.HttpServletResponse;
  4.  
    import javax.servlet.http.HttpSession;
  5.  
    import org.apache.commons.fileupload.FileItemFactory;
  6.  
    import org.apache.commons.fileupload.ProgressListener;
  7.  
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
  8.  
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
  9.  
    import org.apache.log4j.Logger;
  10.  
    import org.springframework.stereotype.Controller;
  11.  
    import org.springframework.web.bind.annotation.RequestMapping;
  12.  
    import org.springframework.web.bind.annotation.RequestMethod;
  13.  
    import org.springframework.web.bind.annotation.ResponseBody;
  14.  
    import org.springframework.web.servlet.ModelAndView;
  15.  
     
  16.  
    @Controller
  17.  
    public class FileUploadController {
  18.  
    Logger log = Logger.getLogger(FileUploadController.class);
  19.  
     
  20.  
    /**
  21.  
    * upload 上传文件
  22.  
    * @param request
  23.  
    * @param response
  24.  
    * @return
  25.  
    * @throws Exception
  26.  
    */
  27.  
    @RequestMapping(value = "/upload.html", method = RequestMethod.POST)
  28.  
    public ModelAndView upload(HttpServletRequest request,
  29.  
    HttpServletResponse response) throws Exception {
  30.  
    final HttpSession hs = request.getSession();
  31.  
    ModelAndView mv = new ModelAndView();
  32.  
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
  33.  
    if(!isMultipart){
  34.  
    return mv;
  35.  
    }
  36.  
    // Create a factory for disk-based file items
  37.  
    FileItemFactory factory = new DiskFileItemFactory();
  38.  
     
  39.  
    // Create a new file upload handler
  40.  
    ServletFileUpload upload = new ServletFileUpload(factory);
  41.  
    upload.setProgressListener(new ProgressListener(){
  42.  
    public void update(long pBytesRead, long pContentLength, int pItems) {
  43.  
    ProcessInfo pri = new ProcessInfo();
  44.  
    pri.itemNum = pItems;
  45.  
    pri.readSize = pBytesRead;
  46.  
    pri.totalSize = pContentLength;
  47.  
    pri.show = pBytesRead+"/"+pContentLength+" byte";
  48.  
    pri.rate = Math.round(new Float(pBytesRead) / new Float(pContentLength)*100);
  49.  
    hs.setAttribute("proInfo", pri);
  50.  
    }
  51.  
    });
  52.  
    List items = upload.parseRequest(request);
  53.  
    // Parse the request
  54.  
    // Process the uploaded items
  55.  
    // Iterator iter = items.iterator();
  56.  
    // while (iter.hasNext()) {
  57.  
    // FileItem item = (FileItem) iter.next();
  58.  
    // if (item.isFormField()) {
  59.  
    // String name = item.getFieldName();
  60.  
    // String value = item.getString();
  61.  
    // System.out.println("this is common feild!"+name+"="+value);
  62.  
    // } else {
  63.  
    // System.out.println("this is file feild!");
  64.  
    // String fieldName = item.getFieldName();
  65.  
    // String fileName = item.getName();
  66.  
    // String contentType = item.getContentType();
  67.  
    // boolean isInMemory = item.isInMemory();
  68.  
    // long sizeInBytes = item.getSize();
  69.  
    // File uploadedFile = new File("c://"+fileName);
  70.  
    // item.write(uploadedFile);
  71.  
    // }
  72.  
    // }
  73.  
    return mv;
  74.  
    }
  75.  
     
  76.  
     
  77.  
    /**
  78.  
    * process 获取进度
  79.  
    * @param request
  80.  
    * @param response
  81.  
    * @return
  82.  
    * @throws Exception
  83.  
    */
  84.  
    @RequestMapping(value = "/process.json", method = RequestMethod.GET)
  85.  
    @ResponseBody
  86.  
    public Object process(HttpServletRequest request,
  87.  
    HttpServletResponse response) throws Exception {
  88.  
    return ( ProcessInfo)request.getSession().getAttribute("proInfo");
  89.  
    }
  90.  
     
  91.  
    class ProcessInfo{
  92.  
    public long totalSize = 1;
  93.  
    public long readSize = 0;
  94.  
    public String show = "";
  95.  
    public int itemNum = 0;
  96.  
    public int rate = 0;
  97.  
    }
  98.  
     
  99.  
    }


但是,如果你的配置文件中有如下配置的话,以上方法就行不通了:

  1.  
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  2.  
    <property name="defaultEncoding" value="UTF-8" />
  3.  
    <property name="maxUploadSize" value="2000000000" />
  4.  
    </bean>



因为这个配置会让你的SpringMVC中servletFileUpload解析为空!

解决办法就是重写CommonsMultipartResolver的parseRequest方法

1、首先将以上的bean注释掉,并加上下面的代码:

  1.  
    <bean id="multipartResolver" class=".../CommonsMultipartResolverExt"> //class为CommonsMultipartResolverExt类的路径
  2.  
    <property name="defaultEncoding" value="UTF-8" />
  3.  
    <property name="maxUploadSize" value="2000000000000" /> //上传文件大小限制
  4.  
    </bean>



2、重写CommonsMultipartResolver的parseRequest方法

  1.  
    import java.util.List;
  2.  
    import javax.servlet.http.HttpServletRequest;
  3.  
    import javax.servlet.http.HttpSession;
  4.  
    import com.smax.ppd.util.FileUploadListener;
  5.  
    import org.apache.commons.fileupload.FileItem;
  6.  
    import org.apache.commons.fileupload.FileUpload;
  7.  
    import org.apache.commons.fileupload.FileUploadBase;
  8.  
    import org.apache.commons.fileupload.FileUploadException;
  9.  
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
  10.  
    import org.springframework.web.multipart.MaxUploadSizeExceededException;
  11.  
    import org.springframework.web.multipart.MultipartException;
  12.  
    import org.springframework.web.multipart.commons.CommonsMultipartResolver;
  13.  
     
  14.  
    public class CommonsMultipartResolverExt extends CommonsMultipartResolver {
  15.  
    @Override
  16.  
    protected MultipartParsingResult parseRequest(HttpServletRequest request)
  17.  
    throws MultipartException {
  18.  
    final HttpSession hs = request.getSession();
  19.  
    FileUploadListener listener = new FileUploadListener(hs); //利用构造方法传递参数
  20.  
    String encoding = determineEncoding(request);
  21.  
    FileUpload fileUpload = prepareFileUpload(encoding);
  22.  
    fileUpload.setProgressListener(listener);
  23.  
    try {
  24.  
    List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request);
  25.  
    return parseFileItems(fileItems, encoding);
  26.  
    }
  27.  
    catch (FileUploadBase.SizeLimitExceededException ex) {
  28.  
    throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex);
  29.  
    }
  30.  
    catch (FileUploadException ex) {
  31.  
    throw new MultipartException("Could not parse multipart servlet request", ex);
  32.  
    }
  33.  
    }
  34.  
    }

3、在上传的Controller代码中加上以下两行代码:

  1.  
    CommonsMultipartResolverExt commonsMultipartResolverExt = new CommonsMultipartResolverExt();
  2.  
    commonsMultipartResolverExt.parseRequest(request);


至此,就可以替代之前用bean配置所实现的功能

4、写一个监听类实现ProgressListener

  1.  
    import org.apache.commons.fileupload.ProgressListener;
  2.  
    import javax.servlet.http.HttpSession;
  3.  
     
  4.  
    public class FileUploadListener implements ProgressListener {
  5.  
     
  6.  
    final HttpSession hs;
  7.  
     
  8.  
    public FileUploadListener(HttpSession hs) {
  9.  
    this.hs = hs;
  10.  
    }
  11.  
     
  12.  
    @Override
  13.  
    public void update(long pBytesRead, long pContentLength, int pItems) {
  14.  
    //pBytesRead 已经上传多少字节
  15.  
    //pContentLength 一共多少字节
  16.  
    //pItems 正在上传第几个文件
  17.  
    ProcessInfo pri = new ProcessInfo();
  18.  
    pri.itemNum = pItems;
  19.  
    pri.readSize = pBytesRead;
  20.  
    pri.totalSize = pContentLength;
  21.  
    pri.show = Math.round(new Float(pBytesRead) / new Float(pContentLength)*100)+" %";
  22.  
    pri.rate = Math.round(new Float(pBytesRead) / new Float(pContentLength)*100);
  23.  
    hs.setAttribute("proInfo", pri);
  24.  
    }
  25.  
     
  26.  
    public class ProcessInfo{
  27.  
    public long totalSize = 1;
  28.  
    public long readSize = 0;
  29.  
    public String show = "";
  30.  
    public int itemNum = 0;
  31.  
    public int rate = 0;
  32.  
    }
  33.  
     
  34.  
    }

5、在Controller中写一个获取进度的方法

  1.  
    /**
  2.  
    * process 获取进度
  3.  
    * @param request
  4.  
    * @param response
  5.  
    * @return
  6.  
    * @throws Exception
  7.  
    */
  8.  
    @RequestMapping(value = "assetinfo/process", method = RequestMethod.GET)
  9.  
    @ResponseBody
  10.  
    public Map<String,Object> process(HttpServletRequest request,
  11.  
    HttpServletResponse response) throws Exception {
  12.  
     
  13.  
    Map<String,Object> map = new HashMap<>();
  14.  
     
  15.  
     
  16.  
    FileUploadListener.ProcessInfo processInfo = (FileUploadListener.ProcessInfo)request.getSession().getAttribute("proInfo");
  17.  
    map.put("show", processInfo.show);
  18.  
    map.put("rate", processInfo.rate);
  19.  
     
  20.  
    return map;
  21.  
    }

6、在前端页面按下上传按钮后用js进行处理,代码如下:

  1.  
    $('#saverecord').bind('click',
  2.  
    function(){
  3.  
    $('#addForm').submit(); //如果前端页面的按钮type为submit则此句可以不写
  4.  
    var eventFun = function(){
  5.  
    $.ajax({
  6.  
    type: 'GET',
  7.  
    url: 'assetinfo/process',
  8.  
    data: {},
  9.  
    dataType: 'json',
  10.  
    success : function(data){
  11.  
    $('#proBar').css('width',data.rate+''+'%');
  12.  
    $('#proBar').empty();
  13.  
    $('#proBar').append(data.show);
  14.  
    if(data.rate == 100){
  15.  
    window.clearInterval(intId); // 当文件上传为100%时终止
  16.  
    }
  17.  
    }});};
  18.  
    var intId = window.setInterval(eventFun,1);//不停地调用eventFun方法与后端交互获取进度
  19.  
    });


7、最后是前端jsp页面:

  1.  
    <label class="control-label">上传进度:</label>
  2.  
    <div class="controls">
  3.  
    <div class="progress progress-success progress-striped" style="100%">
  4.  
    <div id = 'proBar' class="bar" style=" 0%"></div>
  5.  
    </div>
  6.  
    </div>



至此,SpringMVC框架整合进度条就全部完成。

原文地址:https://www.cnblogs.com/handsome1013/p/9367290.html