SpringMVC上传文件进度显示

来源:互联网 发布:新浪微博粉丝数据分析 编辑:程序博客网 时间:2024/05/21 23:33

效果图:


FileUploadController.Java

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. import java.io.File;  
  2. import java.util.List;    
  3.   
  4. import javax.servlet.http.HttpServletRequest;    
  5. import javax.servlet.http.HttpServletResponse;    
  6. import javax.servlet.http.HttpSession;    
  7.     
  8.   
  9.   
  10.   
  11. import org.apache.commons.fileupload.FileItem;  
  12. import org.apache.commons.fileupload.FileItemFactory;    
  13. import org.apache.commons.fileupload.ProgressListener;    
  14. import org.apache.commons.fileupload.disk.DiskFileItemFactory;    
  15. import org.apache.commons.fileupload.servlet.ServletFileUpload;    
  16. import org.apache.log4j.Logger;    
  17. import org.springframework.stereotype.Controller;    
  18. import org.springframework.web.bind.annotation.RequestMapping;    
  19. import org.springframework.web.bind.annotation.RequestMethod;    
  20. import org.springframework.web.bind.annotation.ResponseBody;    
  21. import org.springframework.web.servlet.ModelAndView;    
  22.     
  23. @Controller    
  24. public class FileUploadController {    
  25.     Logger log = Logger.getLogger(FileUploadController.class);    
  26.         
  27.     @RequestMapping(value = "/touploadfile", method = RequestMethod.GET)    
  28.     public ModelAndView toUpload(HttpServletRequest request,    
  29.             HttpServletResponse response) throws Exception{  
  30.                 return new ModelAndView("upload2");  
  31.           
  32.     }  
  33.     /**  
  34.      * upload  上传文件  
  35.      * @param request  
  36.      * @param response  
  37.      * @return  
  38.      * @throws Exception  
  39.      */    
  40.     @RequestMapping(value = "/uploadfile2", method = RequestMethod.POST)    
  41.     public ModelAndView upload(HttpServletRequest request,    
  42.             HttpServletResponse response) throws Exception {    
  43.         final HttpSession hs = request.getSession();    
  44.         ModelAndView mv = new ModelAndView();  
  45.         boolean isMultipart = ServletFileUpload.isMultipartContent(request);    
  46.         if(!isMultipart){    
  47.             return mv;    
  48.         }    
  49.         // Create a factory for disk-based file items    
  50.         FileItemFactory factory = new DiskFileItemFactory();    
  51.     
  52.         // Create a new file upload handler    
  53.         ServletFileUpload upload = new ServletFileUpload(factory);    
  54.         upload.setProgressListener(new ProgressListener(){    
  55.                public void update(long pBytesRead, long pContentLength, int pItems) {    
  56.                    ProcessInfo pri = new ProcessInfo();    
  57.                    pri.itemNum = pItems;    
  58.                    pri.readSize = pBytesRead;    
  59.                    pri.totalSize = pContentLength;    
  60.                    pri.show = pBytesRead+"/"+pContentLength+" byte";    
  61.                    pri.rate = Math.round(new Float(pBytesRead) / new Float(pContentLength)*100);    
  62.                    hs.setAttribute("proInfo", pri);    
  63.                }    
  64.             });    
  65.         List<FileItem> items = upload.parseRequest(request);  
  66.         String path = request.getSession().getServletContext().getRealPath("upload");  
  67.         System.out.println(path);  
  68.         for(FileItem item : items){  
  69.             if(item.isFormField()){  
  70.                   
  71.             }else{  
  72.                 System.out.println(path +"/"+  item.getFieldName());  
  73.                 File targetFile = new File(path +"/"+ item.getName());  
  74.                 if(!targetFile.exists()){  
  75.                     targetFile.createNewFile();  
  76.                 }  
  77.                 item.write(targetFile);  
  78.             }  
  79.         }  
  80.         System.out.println("上传文件的个数为:" + items.size());  
  81.         return mv;  
  82.     }    
  83.         
  84.         
  85.     /**  
  86.      * process 获取进度  
  87.      * @param request  
  88.      * @param response  
  89.      * @return  
  90.      * @throws Exception  
  91.      */    
  92.     @RequestMapping(value = "/process", method = RequestMethod.GET)    
  93.     @ResponseBody    
  94.     public Object process(HttpServletRequest request,    
  95.             HttpServletResponse response) throws Exception {    
  96.         return ( ProcessInfo)request.getSession().getAttribute("proInfo");    
  97.     }    
  98.         
  99.     class ProcessInfo{    
  100.         public long totalSize = 1;    
  101.         public long readSize = 0;    
  102.         public String show = "";    
  103.         public int itemNum = 0;    
  104.         public int rate = 0;    
  105.     }    
  106.         
  107. }    

upload.jsp

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


表单提交后页面不跳转,不刷新,留在原页面:


[javascript] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <div class="panel-body">  
  2.     <form id ="firstUpdateForm" action="/demo/upload/firstUpload" method="post"  
  3.         enctype="multipart/form-data" class="form-horizontal" role="form" target="hidden_frame">  
  4.         <div class="modal-body">  
  5.             <div class="form-group">  
  6.             <label class="col-sm-3 control-label">上传文件</label>  
  7.             <div class="col-sm-5">  
  8.                 <input type="file" id="firstDemoImgFile" name="imgFile">  
  9.             </div>  
  10.             </div>  
  11.         </div>  
  12.         <div class="modal-footer">  
  13.             <div id="firstUploadSucceed" style="display: none;">  
  14.                 <strong>新增成功!</strong><span id="firstUploadSucceedMsg"></span>  
  15.             </div>  
  16.             <div id="firstUploadFailed" style="display: none;">  
  17.                 <strong>对不起!新增失败</strong><span id="firstUploadFailedMsg"></span>  
  18.             </div>  
  19.             <button id="createPeriadBtn" type="submit" class="btn btn-default">确定 </button>  
  20.         </div>  
  21.     </form>   
  22.     <iframe name='hidden_frame' id="hidden_frame" style='display:none'></iframe>  
  23. </div>  

form表单提交的target="hidden_frame",这是为了后台处理完成后返回结果刷新name为hidden_frame的iframe,这样就不会刷新当前页面了。
0 0
原创粉丝点击