本次使用的Spring的文件批量上传,前台使用ajax方式,并显示进度条.
导包
<!-- 文件上传下载包 --> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <!-- https://mvnrepository.com/artifact/commons-io/commons-io --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency>
页面代码
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <!-- <script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script> --> <!-- 引入全局 stylesheet 和 script --> <jsp:include page="${contextPath}/views/common/script.jsp"/> <jsp:include page="${contextPath}/views/common/stylesheet.jsp"/> <title>Insert title here</title> </head> <body> <div class="progress" style="display: none;"> <div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style=" 0;"> <span id="checkProgress"></span> </div> </div> <form id="uploadForm" enctype="multipart/form-data"> 用户名:<input type="text" name="user"/><br/> 文件1:<input type="file" name="file"/><br/> 文件2:<input type="file" name="file02"/><br/> </form> <button id="upload">上传文件</button> <form enctype="multipart/form-data" method="post" action="file/upload.action"> 文件3:<input type="file" name="file" multiple="multiple" /><br/> <input type="submit" value="提交"> </form> </body> <script type="text/javascript"> $(function () { var pro; $("#upload").click(function () { //显示样式 $(".progress").show(); pro = setInterval(progress,1000); var formData = new FormData($('#uploadForm')[0]); formData.append("param","bbbbbbbbbbb"); $.ajax({ type: 'post', url: "file/upload.action", data: formData, cache: false, processData: false, contentType: false, }).success(function (data) { alert(data); }).error(function () { clearInterval(pro); $(".progress").css("display","none"); alert("上传失败"); }); }); function progress () { $.ajax({ type: 'post', url: "file/getProgress.action", data: {}, cache: false, processData: false, contentType: "application/json", }).success(function (data) { if(typeof (data.percent) != "undefind" && data.percent != null){ var per = data.percent +'%'; $(".progress-bar").css("width",per); $("#checkProgress").html(per); if(per == "100%"){ clearInterval(pro); $(".progress").hide(); } } console.log(data); }).error(function () { alert("上传失败"); }); } }); </script> </html>
控制层代码
/**
* 文件的上传
* @param request
* @return
*/
@RequestMapping(value="/upload",method = RequestMethod.POST)
@ResponseBody
public Object upload(HttpServletRequest request){
//获取数据测试
String user = request.getParameter("user");
String param = request.getParameter("param");
String contextPath = request.getSession().getServletContext().getRealPath("/data");
String path = contextPath+"/diagrams";
Object[] fileLastName = {".zip",".doc",".docx",".txt",".iso"};
//创建一个通用的多部分解析器
CustomMultipartResolver multipartResolver = new CustomMultipartResolver(request.getSession().getServletContext());
multipartResolver.setDefaultEncoding("utf-8");
//判断是否有文件上传
if(multipartResolver.isMultipart(request)){
//转化成request
MultipartHttpServletRequest multipartRequest =(MultipartHttpServletRequest)(request);
//取得request中的所有文件
Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
Collection<MultipartFile> files = fileMap.values();
int size = files.size();//文件的数量
if(size > 6){
return "上传数量不得大于6个";
}
if(size == 0) {
return "没有文件或者刷新页面重新上传";
}
//遍历上传文件
for (MultipartFile file:files) {
long startMillis = System.currentTimeMillis();//文件上传的开始时间
if(file != null){
String name = file.getName();//获取jsp页面中name中的值
String fileName = file.getOriginalFilename();//获得上传文件的名称
if(StringUtils.isBlank(fileName)){
continue;
}
int lastNum = fileName.lastIndexOf(".");
String suffix = fileName.substring(lastNum, fileName.length());//判断文件的结尾
//判断后缀名是否符合标准
boolean contains = ArrayUtils.contains(fileLastName,suffix);
if(!contains){
return "后缀名不合法";
}
}
try {
String filePath = path+file.getOriginalFilename()+new Date().getTime();
file.transferTo(new File(filePath));
} catch (IOException e) {
e.printStackTrace();
}
}
}
return "上传成功";
}
@RequestMapping(value = "/getProgress",method = RequestMethod.POST)
@ResponseBody
public ProgressEntity initCreateInfo(HttpServletRequest request) {
ProgressEntity status = (ProgressEntity) request.getSession().getAttribute("status");
if(status==null){
return new ProgressEntity();
}
return status;
}
Spring整合
<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
<bean id="multipartResolver" class="ch.system.rebean.CustomMultipartResolver">
<!-- <property name="maxUploadSize" value="3"/>
<property name="maxInMemorySize" value="4096"/>-->
<property name="defaultEncoding" value="UTF-8"></property>
</bean>
文件上传的重写
package ch.system.rebean; import ch.system.listener.MyProgressListener; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUpload; import org.apache.commons.fileupload.FileUploadBase; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.multipart.MaxUploadSizeExceededException; import org.springframework.web.multipart.MultipartException; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import java.util.List; /** * Description:对上传文件的重写 * * @author cy * @date 2018年08月06日 18:05 * version 1.0 */ public class CustomMultipartResolver extends CommonsMultipartResolver { @Autowired private MyProgressListener progressListener; public CustomMultipartResolver() { } public CustomMultipartResolver(ServletContext servletContext) { super(servletContext); } public void setFileUploadProgressListener(MyProgressListener progressListener){ this.progressListener=progressListener; } @Override public MultipartParsingResult parseRequest(HttpServletRequest request) throws MultipartException { String encoding = determineEncoding(request); FileUpload fileUpload = prepareFileUpload(encoding); progressListener.setSession(request.getSession()); fileUpload.setProgressListener(progressListener); try { List<FileItem> fileItems = ((ServletFileUpload) fileUpload).parseRequest(request); return parseFileItems(fileItems, encoding); } catch (FileUploadBase.SizeLimitExceededException ex) { throw new MaxUploadSizeExceededException(fileUpload.getSizeMax(), ex); } catch (FileUploadException ex) { throw new MultipartException("Could not parse multipart servlet request", ex); } } }
进度条bean
package ch.system.bean; /** * Description:文件下载读取文件的bean * * @author cy * @date 2018年08月06日 18:10 * version 1.0 */ public class ProgressEntity { private long pBytesRead = 0L; //到目前为止读取文件的比特数 private long pContentLength = 0L; //文件总大小 private int pItems; //目前正在读取第几个文件 private int percent; // 完成比例 private long startTime = System.currentTimeMillis(); //开始时间 private long useTime = System.currentTimeMillis(); //已用时间 public long getpBytesRead() { return pBytesRead; } public void setpBytesRead(long pBytesRead) { this.pBytesRead = pBytesRead; } public long getpContentLength() { return pContentLength; } public void setpContentLength(long pContentLength) { this.pContentLength = pContentLength; } public int getpItems() { return pItems; } public void setpItems(int pItems) { this.pItems = pItems; } public int getPercent() { return percent; } public void setPercent(int percent) { this.percent = percent; } public long getStartTime() { return startTime; } public void setStartTime(long startTime) { this.startTime = startTime; } public long getUseTime() { return useTime; } public void setUseTime(long useTime) { this.useTime = useTime; } @Override public String toString() { float tmp = (float)pBytesRead; float result = tmp/pContentLength*100; return "ProgressEntity [pBytesRead=" + pBytesRead + ", pContentLength=" + pContentLength + ", percentage=" + result + "% , pItems=" + pItems + "]"; } }
监听器
package ch.system.listener; import ch.system.bean.ProgressEntity; import org.apache.commons.fileupload.ProgressListener; import org.springframework.stereotype.Component; import javax.servlet.http.HttpSession; /** * Description:文件上传的监听器 * * @author cy * @date 2018年08月06日 17:59 * version 1.0 */ @Component public class MyProgressListener implements ProgressListener { private HttpSession session; public void setSession(HttpSession session){ this.session=session; ProgressEntity status = new ProgressEntity(); session.setAttribute("status", status); } @Override public void update(long pBytesRead, long pContentLength, int pItems) { ProgressEntity status = (ProgressEntity) session.getAttribute("status"); status.setpBytesRead(pBytesRead); status.setpContentLength(pContentLength); status.setpItems(pItems); status.setUseTime(System.currentTimeMillis()-status.getStartTime()); status.setPercent((int)(pBytesRead*100/pContentLength)); //完成的计算已完成pBytesRead/1024/1024 M } }
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <!-- <script src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script> --> <!-- 引入全局 stylesheet 和 script --> <jsp:include page="${contextPath}/views/common/script.jsp"/> <jsp:include page="${contextPath}/views/common/stylesheet.jsp"/> <title>Insert title here</title></head><body>
<div class="progress" style="display: none;"> <div class="progress-bar" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style=" 0;"> <span id="checkProgress"></span> </div></div>
<form id="uploadForm" enctype="multipart/form-data"> 用户名:<input type="text" name="user"/><br/> 文件1:<input type="file" name="file"/><br/> 文件2:<input type="file" name="file02"/><br/></form><button id="upload">上传文件</button>
<form enctype="multipart/form-data" method="post" action="file/upload.action"> 文件3:<input type="file" name="file" multiple="multiple" /><br/> <input type="submit" value="提交"></form>
</body>
<script type="text/javascript"> $(function () { var pro; $("#upload").click(function () { //显示样式 $(".progress").show(); pro = setInterval(progress,1000); var formData = new FormData($('#uploadForm')[0]); formData.append("param","bbbbbbbbbbb"); $.ajax({ type: 'post', url: "file/upload.action", data: formData, cache: false, processData: false, contentType: false, }).success(function (data) { alert(data); }).error(function () { clearInterval(pro); $(".progress").css("display","none"); alert("上传失败"); }); }); function progress () { $.ajax({ type: 'post', url: "file/getProgress.action", data: {}, cache: false, processData: false, contentType: "application/json", }).success(function (data) { if(typeof (data.percent) != "undefind" && data.percent != null){ var per = data.percent +'%'; $(".progress-bar").css("width",per); $("#checkProgress").html(per); if(per == "100%"){ clearInterval(pro); $(".progress").hide(); } } console.log(data); }).error(function () { alert("上传失败"); }); }
});</script>
</html>