Spring MVC 上传文件

Spring MVC上传文件需要如下步骤:

  1、前台页面,form属性 method设置为post,enctype="multipart/form-data"  input的type类型设置为file。

   <h>添加用户</h>
<form name="userForm" action="/file/upload2" method="post" enctype="multipart/form-data" >
选择文件:<input type="file" name="file"> <input type="submit" value="上传" >
</form>

  2、引入jar包commons-fileupload.jar以及commons-io.jar包

  3、在spring配置文件bean 注入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>

  4.1、controller里面方法的参数处使用@RequestParam("file") CommonsMultipartFile file,指定传过来的file是CommonsMultipartFile类型
     然后即可使用IO读写文件。

    @RequestMapping("/upload")
public String addUser(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest request) throws IOException{
System.out.println("fileName---->" + file.getOriginalFilename()); if(!file.isEmpty()){
try {
FileOutputStream os = new FileOutputStream("D:/" + new Date().getTime() + file.getOriginalFilename());
InputStream in = file.getInputStream();
int b = 0;
while((b=in.read()) != -1){
os.write(b);
}
os.flush();
os.close();
in.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "/success";
}

  4.2、或者在controller直接使用spring自带的封装了的文件上传类org.springframework.web.multipart.commons.CommonsMultipartFile以及
      org.springframework.web.multipart.commons.CommonsMultipartResolver

    @RequestMapping("/upload2")
public String upload2(HttpServletRequest request,HttpServletResponse response) throws IllegalStateException, IOException{
//
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
if(multipartResolver.isMultipart(request)){
//需要有表单域name属性,否则将取不到对应的file
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request; Iterator<String> iter = multiRequest.getFileNames();
while(iter.hasNext()){
MultipartFile file = multiRequest.getFile((String)iter.next());
if(file != null){
String fileName = "demoUpload" + file.getOriginalFilename();
String path = "D:/" + fileName; File localFile = new File(path); file.transferTo(localFile);
}
}
}
return "/success";
}
上一篇:Spring MVC上传文件


下一篇:uploadify上传文件(2)--基础语法