话不多说直接上代码
1 <%@ page language="java" contentType="text/html; charset=UTF-8" 2 pageEncoding="UTF-8"%> 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 4 <html> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 7 <script type="text/javascript" src="../3rd/jquery-3.2.1.min.js"></script> 8 9 <style type="text/css"> 10 11 .modelContent{ 12 width: 380px; 13 height: 150px; 14 margin: 100px 200px; 15 background-color: #FFFFFF; 16 z-index: 1050; 17 position: absolute; 18 19 } 20 21 .hidden{ 22 display: none; 23 } 24 25 .content { 26 position: relative; 27 width: 350px; 28 margin: 30px 20px; 29 30 } 31 32 .txt { 33 height: 22px; 34 border: 1px solid #cdcdcd; 35 width: 180px; 36 vertical-align: middle; 37 margin: 0; 38 padding: 0 39 } 40 41 .btn { 42 border: 1px solid #CDCDCD; 43 height: 24px; 44 width: 70px; 45 vertical-align: middle; 46 margin: 0; 47 padding: 0 48 } 49 50 .file { 51 position: absolute; 52 top: 0; 53 left: 190px; 54 height: 24px; 55 filter: alpha(opacity : 0); 56 opacity: 0; 57 width: 70px; 58 vertical-align: middle; 59 margin: 0; 60 padding: 0 61 } 62 63 .backdrop{ 64 position: fixed; 65 z-index: 1040; 66 background-color: #333; 67 opacity: .5; 68 width: 100%; 69 height: 100%; 70 } 71 72 .header{ 73 padding: 15px; 74 border-bottom: 1px solid #e5e5e5; 75 } 76 77 .close:focus, .close:hover { 78 color: #000; 79 text-decoration: none; 80 cursor: pointer; 81 opacity: .5; 82 } 83 84 .close{ 85 float: right; 86 margin-top: -9px; 87 } 88 89 </style> 90 </head> 91 92 <body> 93 <!-- 附于body之上的div --> 94 <div class="hidden backdrop" id="backDiv"></div> 95 96 <!-- 定义上传按钮 --> 97 <button type="button" class="btn btn-default" title="导入" id="export"> 98 </button> 99 100 <!-- 定义上传对话框 --> 101 <div class="modelContent hidden" id="uploadDialog"> 102 <!-- 标题 --> 103 <div class="header"> 104 <span class="close">x</span> 105 </div> 106 <!-- 内容 --> 107 <div class="content"> 108 <input type="text" id="textfield" class="txt" disabled="disabled"/> 109 <input type="button" class="btn" value="浏览..." /> 110 <input type="file" name="file" class="file" id="file" multiple/> 111 <!-- onchange="document.getElementById('textfield').value=this.value" --> 112 <input type="submit" id="submit" class="btn" value="上传"/> 113 </div> 114 <!-- 上传进度条 --> 115 <div class="hidden" id="progressDiv" style="margin: 0px 15px;"> 116 <progress id="progressbar" value="0" max="100" style=" 308px;"> 117 </progress> 118 <span id="percentage" style="color: blue;"></span> 119 </div> 120 </div> 121 </body> 122 123 <script type="text/javascript"> 124 $(function(){ 125 $("#export").click(function(){ 126 $("#uploadDialog,#backDiv").removeClass("hidden"); 127 $("body").css("background-color","#fff"); 128 }); 129 130 //将选择的文件写到text中 131 $("#file").change(function(e){ 132 var nameArray = []; 133 var files = $("#file")[0].files; 134 $.each(files,function(index,val){ 135 nameArray.push(val.name); 136 }); 137 $("#textfield").val(nameArray.join()); 138 }) 139 140 //关闭上传对话框 141 $(".close").click(function(e){ 142 $("#uploadDialog,#backDiv").addClass("hidden"); 143 $("#textfield").val(""); 144 }); 145 146 //点击上传,由于非form表单上传,因此采用 147 $("#submit").click(function(e){ 148 //显示进度条 149 $("#progressDiv").show(); 150 //获取上传文件 151 var fileObj = $("#file")[0].files[0]; 152 console.log(fileObj); 153 //使用formdata实现无刷新上传 154 var formData = new FormData(); 155 formData.append("file",fileObj); 156 //后台使用springmvc接收请求 157 var url = "http://localhost:8080/SpringMVCTest/index/fileUpload"; 158 //ajax 159 var xhr = new XMLHttpRequest(); 160 xhr.open("POST",url,true); 161 //定义上传对象的进度事件 162 xhr.upload.onprogress=function(event){ 163 var progressBar = document.getElementById("progressbar") ; 164 var percentageDiv = document.getElementById("percentage"); 165 if (event.lengthComputable) { 166 progressBar.max = event.total; 167 progressBar.value = event.loaded; 168 percentageDiv.innerHTML = Math.round(event.loaded / event.total * 100)+ "%"; 169 } 170 }; 171 172 // //当状态为4, 173 xhr.onload = function(event){ 174 //获取相应的状态 175 var data = xhr.responseText; 176 //关闭进度条,并显示上传成功状态 177 // $("#progressDiv").addClass("hidden"); 178 // 179 }; 180 xhr.send(formData); 181 }); 182 }) 183 </script> 184 </html>
几点提示:
1. 模态框的处理中必须增加一个影藏的div,设置其高、宽均为100%,当模态框显示时只需要其z-index的值大于背景div即可。
2. post的请求体必须使用FormData来传递,否则后台无法接受到文件信息。
后台处理使用springmvc,务必注意以下几点,
1. 在spring-mvc.xml中配置CommonsMultipartResolver的mutipart解析类
1 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 2 <property name="defaultEncoding" value="UTF-8"></property> 3 <property name="maxUploadSize" value="10485760000"></property> 4 <property name="maxInMemorySize" value="10240000"></property> 5 </bean>
2. 如果需要进度条显示,则需要实现进度监听类ProgressListener
1 package com.yongcheng.liuyang.listener; 2 3 import javax.servlet.http.HttpSession; 4 import org.apache.commons.fileupload.ProgressListener; 5 import org.springframework.stereotype.Component; 6 7 import com.yongcheng.liuyang.model.Progress; 8 9 @Component 10 public class FileUploadProgressListener implements ProgressListener { 11 private HttpSession session; 12 public void setSession(HttpSession session){ 13 this.session=session; 14 Progress status = new Progress();//保存上传状态 15 session.setAttribute("status", status); 16 } 17 public void update(long pBytesRead, long pContentLength, int pItems) { 18 Progress status = (Progress) session.getAttribute("status"); 19 try { 20 Thread.sleep(5); 21 } catch (InterruptedException e) { 22 e.printStackTrace(); 23 } 24 status.setpBytesRead(pBytesRead); 25 status.setpContentLength(pContentLength); 26 status.setpItems(pItems); 27 28 } 29 30 }
3. 如果实现了进度监听接口,则需要将进度信息写到文件的解析类中,因此必须继承CommonsMultipartResolver,覆写parseRequest方法
1 package com.yongcheng.liuyang.listener; 2 3 import java.util.List; 4 5 import javax.servlet.http.HttpServletRequest; 6 7 import org.apache.commons.fileupload.FileItem; 8 import org.apache.commons.fileupload.FileUpload; 9 import org.apache.commons.fileupload.FileUploadBase; 10 import org.apache.commons.fileupload.FileUploadException; 11 import org.apache.commons.fileupload.servlet.ServletFileUpload; 12 import org.springframework.beans.factory.annotation.Autowired; 13 import org.springframework.web.multipart.MaxUploadSizeExceededException; 14 import org.springframework.web.multipart.MultipartException; 15 import org.springframework.web.multipart.commons.CommonsMultipartResolver; 16 17 public class CustomMultipartResolver extends CommonsMultipartResolver { 18 19 @Autowired 20 private FileUploadProgressListener progressListener; 21 22 public void setFileUploadProgressListener( 23 FileUploadProgressListener progressListener) { 24 this.progressListener = progressListener; 25 } 26 27 @Override 28 @SuppressWarnings("unchecked") 29 public MultipartParsingResult parseRequest(HttpServletRequest request) 30 throws MultipartException { 31 String encoding = determineEncoding(request); 32 FileUpload fileUpload = prepareFileUpload(encoding); 33 progressListener.setSession(request.getSession()); 34 fileUpload.setProgressListener(progressListener); 35 try { 36 List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request); 37 return parseFileItems(fileItems, encoding); 38 } 39 catch (FileUploadBase.SizeLimitExceededException ex) { 40 throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex); 41 } 42 catch (FileUploadException ex) { 43 throw new MultipartException("Could not parse multipart servlet request", ex); 44 } 45 } 46 }
如有问题,欢迎评论留言,共同进步!!