springmvc-文件上传

 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  }

 

posted @ 2014-11-06 18:21  放手风筝  阅读(150)  评论(0编辑  收藏  举报