1.JSP
<!-- Modal --> <div class="modal fade" id="myProblem" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" style="padding-top: 8%"> <div class="modal-dialog" style="width: 50%"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h4 class="modal-title">新建问题</h4> </div> <div class="modal-body"> <form action="#" class="form-horizontal " id="formdata" method="post" enctype="multipart/form-data"> <div class="form-group"> <label class="control-label col-md-3">跟踪:</label> <div class="col-md-2"> <select class="form-control" id="tail" name="tail"> <option>需求</option> <option>任务</option> </select> </div> </div> <div class="form-group"> <label class="control-label col-md-3">主题:</label> <div class="col-md-7 col-xs-11"> <input class="form-control" type="text" id="theme" name="theme"> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">描述:</label> <div class="col-md-7 col-xs-11"> <textarea rows="6" class="form-control" id="describle" name="describle"></textarea> </div> <input style="margin-left: 27%" id="file" type="file" name="multipleFileUpload" multiple /> </div> <div class="form-group"> <label class="control-label col-md-3">优先级:</label> <div class="col-md-2"> <select class="form-control" id="priority"> <option>紧急</option> <option>一般</option> </select> </div> <label class="control-label col-md-2">计划完成日期:</label> <div class="col-md-3 col-xs-11"> <div class='input-group date' id='datetimepicker2'> <input type='text' name="ttime" class="form-control" /> <span class="input-group-addon"> <span class="glyphicon glyphicon-calendar"></span> </span> </div> </div> </div> <div class="form-group"> <label class="control-label col-md-3">指派给:</label> <div class="col-md-2"> <select class="form-control" id="user"> <c:forEach items="${users}" var="user"> <option>${user.username}</option> </c:forEach> </select> </div> <label class="control-label col-md-2">网站:</label> <div class="col-md-3 col-xs-11"> <select class="form-control" id="netname"> <c:forEach items="${netNames}" var="netName"> <option>${netName.nename}</option> </c:forEach> </select> </div> </div> </form> </div> <div class="modal-footer"> <button class="btn btn-success" type="button" id="addProblem">提交</button> <button data-dismiss="modal" class="btn btn-default" type="button">取消</button> </div> </div> </div> </div> <!-- modal -->
2.JS
$("#addProblem").click(function() { $("#myProblem").modal('hide'); var iden=1; /* var fileName = $('#file').val().split('\\'); //得到文件名数组 */ var files = document.getElementById('file').files; //获得文件大小; if(files.length>0){ for(var i=0;i<files.length;i++){ filePath = files[i].name.split('.'); fileType = filePath[filePath.length-1]; console.log(fileType); if(!(fileType == "png" || fileType == "jpg" || fileType == "xlsx"|| fileType == "docx"|| fileType == "rar" || fileType == "zip" )){ alert('文件格式不符合要求!'); iden=0; break }else if(files[i].size>10485760){ alert('错误!请上传不超过10M的文件'); iden=0; break }else{ iden=1; } } } if(iden==1){ var formData = new FormData($("#formdata")[0]); formData.append("tail", $("#tail option:selected").text()); formData.append("priority", $("#priority option:selected").text()); formData.append("user", $("#user option:selected").text()); formData.append("netname", $("#netname option:selected").text()); formData.append("operator", $("#username").text()); formData.append("user", $("#user option:selected").text()); $.ajax({ url : "${ctx}/addProblem", type : "POST", data : formData, async : false, cache : false, contentType : false, processData : false, success : function(returndata) { var re = JSON.parse(returndata); $("#msg").html(re); $("#publicModel").modal('show'); setTimeout("hide()", 1000); to_page(1); }, error : function(returndata) { var re = JSON.parse(returndata); $("#msg").html(re); $("#publicModel").modal('show'); setTimeout("hide()", 1000); to_page(1); } }); } });
3.controller接收
@RequestMapping("/addProblem") @ResponseBody public String addProblem(HttpServletRequest request) throws Exception{ String describle= request.getParameter("describle"); String tail= request.getParameter("tail"); String theme= request.getParameter("theme"); String priority= request.getParameter("priority"); String processor= request.getParameter("user"); String netname= request.getParameter("netname"); String ttime= request.getParameter("ttime"); String operator= request.getParameter("operator"); //使用springmvc提供的方法来处理文件 //初始化解析器 CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); String path =""; String fileName =""; //判断request中是否有multipartResolver类型数据,有就表示有文件类型 if(multipartResolver.isMultipart(request)){ MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; //获得文件名,这里是迭代器封装 Iterator iter = multiRequest.getFileNames(); while(iter.hasNext()){ //这是前台name字段的名字,比如这里是filename String filename = (String) iter.next(); String filename1=""; //根据name字段来获得MultipartFile // MultipartFile file1 = multiRequest.getFile(filename);单个文件 List<MultipartFile> files = new LinkedList<MultipartFile>(); files =multiRequest.getFiles(filename); System.out.println(files); for (MultipartFile file : files) { if (file != null) { if (file.getOriginalFilename()==null||file.getOriginalFilename().equals("")) { }else{ filename1 = new Date().getTime()+file.getOriginalFilename(); path ="D:\\EclipseProject\\webapp\\File\\"+filename1; //注意:文件要保存在项目文件webapp下面 File localFile = new File(path); //Springmvc 提供的写文件方法 file.transferTo(localFile); } } fileName+=filename1+";"; } } } SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); userService.selectUserEntityByUsername(processor); Problem problem = new Problem(tail, "新问题", theme, describle, fileName, priority,df.format(new Date()),ttime, null, processor, netname,operator); boolean result =problemService.insert(problem); return result?"提交成功":"提交失败"; }
4.页面显示文件
<c:choose> <c:when test="${problem.path== '' }"> </c:when> <c:otherwise> <%-- <a href="${ctx}/File/${problem.path}" download=""><i class="fa fa-paperclip"></i>${problem.path}</a> --%> ${problem.path} 多个文件的名称字符串 <c:if test="${not empty problem.path}"> <c:set value="${fn:split(problem.path,';')}" var="paths" /> <p style="text-align: left;"> <c:forEach items="${paths}" var="path"> <div><a href="${ctx}/File/${path}" download="" style="color:grey;text-decoration:blink"><i class="fa fa-paperclip"></i>${path}</a></div> </c:forEach> </p> </c:if> </c:otherwise> </c:choose> 注意:这里要在JSP最上面加上 <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>