SpringMVC上传文件

  SpringMVC中上传文件还是比较方便的,Spring内置了一些上传文件的支持类,不需要复杂的操作即可上传文件。

  文件上传需要两个jar支持,一个是commons-fileupload.jar和commons-io.jar。并且需要在springMVC的配置文件中加入支持文件上传的配置:

  

1 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
2     <property name="defaultEncoding" value="utf-8" />
3 </bean>

  可配置项还有maxuploadsize、uploadTempDir、maxInMemorySize等等。

  jsp页面代码:

1 <body>
2       <form action="<%=path %>/upload" method="post" enctype="multipart/form-data">
3           文件:<input type="file" name="file" id="file" /><br/>
4           参数:<input type="text" name="param" id="param" /><br/>
5               <button type="submit">提交</button>
6       </form>
7  </body>

  文件上传的controller代码:

  

 1 import java.io.File;
 2 import java.io.IOException;
 3 import javax.servlet.http.HttpServletRequest;
 4 import org.springframework.stereotype.Controller;
 5 import org.springframework.web.bind.annotation.RequestMapping;
 6 import org.springframework.web.bind.annotation.RequestParam;
 7 import org.springframework.web.multipart.MultipartFile;
 8 
 9 @Controller
10 public class UploadController{
11     
12     @RequestMapping("/upload")
13     public String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request){
14         if(file.isEmpty()){
15             System.out.println("file is null---");
16             return null;
17         }
18         
19         try {
20             String fileName = file.getOriginalFilename();
21             fileName = new String(fileName.getBytes("iso8859-1"), "UTF-8"); //防止文件名中的中文乱码,进行utf-8转码
22             
23             String newPath = request.getSession().getServletContext().getRealPath("upload"); //使用项目下的upload目录存放上传的文件
24             String param = request.getParameter("param");  //获取到表单提交的参数
25             System.out.println("param:"+param);
26             File newFile2 = new File(newPath);
27             if(!newFile2.exists()){
28                 newFile2.mkdir();
29             }
30             File newFile = new File(newPath+File.separator+fileName);
31             file.transferTo(newFile);  // 存储文件
32         } catch (IOException e) {
33             e.printStackTrace();
34         }
35         return null;
36     }
37 }
原文地址:https://www.cnblogs.com/bigbang92/p/springMVC-fileupload.html