1.配置xml文件
1 <!-- 指定文件上传解析 名字不能乱给 --> 2 <bean name="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 3 <property name="defaultEncoding" value="utf-8" /> 4 <property name="maxUploadSize" value="9223372036854775807" /> 5 </bean>
2.编写代码
1 @RequestMapping(value="flatform/app/appinfoaddsave") 2 public String appinfoaddsave(App_info app_info, MultipartFile a_logoPicPath, Model m, HttpSession session) throws IOException { 3 if (a_logoPicPath.getSize() > 1024*50) { 4 m.addAttribute("fileUploadError", "文件大小不能超过50kb!"); 5 return "jsp/developer/appinfoadd"; 6 } 7 String filename = a_logoPicPath.getOriginalFilename(); //文件名称 8 String contextPath = session.getServletContext().getContextPath(); //相对路径 9 String realPath = session.getServletContext().getRealPath("statics/uploadfiles"); //绝对路径 10 String type = a_logoPicPath.getContentType(); //文件类型 11 File file = new File(realPath, filename); 12 if ("image/png".equals(type) || "image/jpg".equals(type) || "image/jpeg".equals(type)) { 13 a_logoPicPath.transferTo(file); //将图片保存到本地 14 app_info.setLogoLocPath(realPath+"\"+filename); 15 app_info.setLogoPicPath(contextPath+"/statics/uploadfiles/"+filename); 16 app_infoService.appinfoaddsave(app_info); 17 return "redirect:list"; 18 } else { 19 m.addAttribute("fileUploadError", "文件类型只能是jpg、jpeg、png!"); 20 return "jsp/developer/appinfoadd"; 21 } 22 }
最后需要再jsp页面中的form标签中加上 enctype="multipart/form-data"。
注意:jsp页面中文件控件的name属性和MultipartFile参数名称要相同,否则spring mvc映射不到,文件自然接收不到。
如果名称实在是不想写成一样的话,可以MultipartFile参数前加@RequestParam("控件的name属性")来映射。