使用springMVC上传文件

control层实现功能:

@RequestMapping(value="upload2")
public String upLoad2(HttpServletRequest request, HttpServletResponse response) 
   throws IllegalStateException, IOException{
    //解析器解析request的上下文
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); 
    //先判断request中是否包涵multipart类型的数据,
    if(multipartResolver.isMultipart(request)){
     //再将request中的数据转化成multipart类型的数据
     MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
     Iterator iter = multiRequest.getFileNames();
      while(iter.hasNext()){
        MultipartFile file = multiRequest.getFile((String)iter.next());
        if(file != null){
           String fileName = file.getOriginalFilename();
           String path = "D:/" + fileName;
           File localFile = new File(path);
           //写文件到本地
           file.transferTo(localFile);
        }
     }
  }
  return "/success";
}

JSP文件:

<form name="upload" action="/springMVC9/file/upload2" enctype="multipart/form-data" method="post">
  <input type="file" name="thefile" /> <input type="submit" value="上传文件" />
</form>

在springMVC配置文件中添加解析器:

<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 --> 
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="defaultEncoding" value="utf-8" />
      <property name="maxUploadSize" value="10485760000" />
    <property name="maxInMemorySize" value="40960" />
</bean>

 

posted @ 2017-04-06 18:59  岁月淡忘了谁  阅读(218)  评论(0编辑  收藏  举报