1 在doc文檔中搜索MultipartResolver 2 3 step1:在配置文件中增長對文件上傳的配置 準備工做,準備一個表單而且表單的enctype="multipart/form-data" 4 由於springmvc使用的是commons-upload上傳組件,因此要導入兩個jar文件分別爲commons-upload.ar commons-io.jar 5 <!-- 配置文件上傳的resolver --> 6 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> 7 <property name="defaultEncoding" value="UTF-8"/> 8 <!-- 指定所上傳文件的總大小不能超過200KB。注意maxUploadSize屬性的限制不是針對單個文件,而是全部文件的容量之和 --> 9 <property name="maxUploadSize" value="500000"/> 10 </bean> 11 12 step2:在一個方法中進行測試 13 /** 14 * post請求方式實現真正的添加 15 * 使用bean validation 16 * BindingResult br 必須在@valid後面 17 * @return 18 * @throws IOException 19 */ 20 @RequestMapping(value={"/add"}, method=RequestMethod.POST) 21 public String add(@Validated User user, BindingResult br,@RequestParam("attachments") MultipartFile[] attachments, HttpServletRequest req) throws IOException 22 { 23 24 if(br.hasErrors()) 25 { 26 //出錯 27 return "user/add"; 28 29 //文件上傳 } 30 for(MultipartFile attachment : attachments) 31 { 32 //若是文件爲空那麼將跳過 33 if(attachment.isEmpty()) continue; 34 //上傳單個文件使用MultipartFile能夠上傳一個文件若是要上傳多個文件的話要使用數組 35 //上傳多個文件使用數組的方式,而且要在數組參數以前加一個@RequestParam(name),應爲它不知道對應的類型 ,否者會拋出異常 36 System.out.println(attachment.getName() + "-" + attachment.getOriginalFilename() + "-" + attachment.getContentType()); 37 //建立對應的文件 38 String path = req.getSession().getServletContext().getRealPath("/upload"); 39 File file = new File(path); 40 map.put(user.getUserName(), user); 41 FileUtils.copyInputStreamToFile(attachment.getInputStream(), new File(path, attachment.getOriginalFilename())); 42 } 43 return "redirect:/user/list"; 44 }