SpringMVC上传文件进度显示

效果图:


FileUploadController.java


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

upload.jsp


  
  
  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. </div>
  19. <div class="controls">
  20. <input type="file" name="file" style="width:550">
  21. </div>
  22. <div class="controls">
  23. <input type="file" name="file" style="width:550">
  24. </div>
  25. <label class="control-label">上传进度: </label>
  26. <div class="controls">
  27. <div class="progress progress-success progress-striped" style="width:50%">
  28. <div id = 'proBar' class="bar" style="width: 0%"> </div>
  29. </div>
  30. </div>
  31. </div>
  32. <div class="control-group">
  33. <div class="controls">
  34. <button type="button" id="subbut" class="btn">submit </button>
  35. </div>
  36. </div>
  37. </form>
  38. <iframe name="uploadf" style="display:none"> </iframe>
  39. </body>
  40. </html>
  41. <script type="text/javascript">
  42. $( document).ready( function() {
  43. $( '#subbut').bind( 'click', function() {
  44. $( '#fForm').submit();
  45. var eventFun = function() {
  46. $.ajax({
  47. type : 'GET',
  48. url : 'process',
  49. data : {},
  50. dataType : 'json',
  51. success : function(data) {
  52. $( '#proBar').css
  53. ( 'width', data.rate + '' + '%');
  54. $( '#proBar').empty();
  55. $( '#proBar').append(data.show);
  56. if (data.rate == 100) {
  57. window.clearInterval(intId);
  58. }
  59. }
  60. });
  61. };
  62. var intId = window.setInterval(eventFun, 500);
  63. });
  64. });
  65. </script>


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



  
  
  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为 hidde n_frame的iframe,这样就不会刷新当前页面了。
原文地址:https://blog.csdn.net/wzygis/article/details/51364157

猜你喜欢

转载自blog.csdn.net/tongshuixu8025/article/details/85777045