1、前期准备:
Spring文件上传操作,此文中是基于Commons FileUpload 的文件上传
maven 管理jar包,在pom.xml 添加commons-fileupload.jar的依赖:
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.2.2</version> </dependency>
由于Post一个包含文件上传的Form会以multipart/form-data请求发送给服务器,必须要通知DispatcherServlet如何处理MultipartRequest请求:
<!--文件上传--> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver" p:defaultEncoding="utf-8" p:maxUploadSize="1048576" />
3、Controller的编写:
/** * 文件上传控制。 * @author xialong<mailto:[email protected]> * @param request * @return */ @ResponseBody @RequestMapping(value = "/xlsUpload.json",method=RequestMethod.POST) public Map<String,Object> xlsUpload(HttpServletRequest request) { Map<String,Object> map = new HashMap<String,Object>(); try { // 转型为MultipartHttpRequest: MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; // 获得文件: MultipartFile file = multipartRequest.getFile("file"); // 获得文件名: String filename = file.getOriginalFilename(); System.out.println(filename); // 获得输入流: InputStream input = file.getInputStream(); map.put("code", "S"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); map.put("code", "E"); } return map; }
这地方用到了jquery.form 来进行异步的表单提交。请下载最新的jquer.form.js;
<head> <script src="${pageContext.request.contextPath}/scripts/jquery/jquery-1.7.2.js" type="text/javascript"></script> <script src="${pageContext.request.contextPath}/scripts/jquery/jquery.form.js" type="text/javascript"></script> <script> $(document).ready(function(){ $('#xlsForm').ajaxForm({ url:'/file/xlsUpload.json', type:'post', dataType: 'json', success:function (data){ if(data.code == "S"){ alert("success!!!"); }else{ alert("error "); } }, error:function(data){ alert("未知异常"); } }); }); function dosubmit(){ var fileName = $('#fileInfo').val(); alert(fileName); if('' == fileName) { alert("请选择上传文件"); return; } var bingIndex = fileName.lastIndexOf('.'); if(-1 == bingIndex) { alert("上传文件格式错误"); return; } var suffix = fileName.substring(bingIndex + 1, fileName.length); if('xls' == suffix) { $('#xlsForm').submit(); } else { alert("上传文件必须是已“xls”为后缀的Excel文件"); } } </script> </head> <body> <form id="xlsForm" method="post" enctype="multipart/form-data" > <input id="fileInfo" type="file" name="file" /> <input id="xlsBut" type="button" value="upload" onclick="dosubmit()" /> </form> </body>