Spring MVC文件上傳
阿新 • • 發佈:2017-08-26
nbsp exception ans 文件 etc contex 配置 tex ppi
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(); //相對路徑 9String 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"。
Spring MVC文件上傳