Spring MVC+Maven 轻松实现上传文件功能

来源:互联网 发布:数据分析师市场需求 编辑:程序博客网 时间:2024/06/06 08:29

在做上传文件功能时,首先得有一个建立完毕的Spring MVC项目。这里我以Spring MVC的HelloWord工程来示例,当然你也可以在你已有的Spring MVC工程下进行操作。

建立Spring MVC的HelloWord工程的步骤请参考文章:手把手教你创建一个Maven+Spring MVC的HelloWorld

Spring MVC的HelloWord工程的源码:http://download.csdn.net/detail/u012660464/9695653

下面分别记录下如何上传单个文件和上传多个文件。


一、上传单个文件


步骤如下:


1、在前端控制器配置文件(本项目所取的名字是:spring-mvc-servlet.xml)中加入上传文件所需的Bean。

[html] view plain copy
  1. <!--200*1024*1024即200M resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常 -->  
  2.   
  3.  <bean id="multipartResolver"  
  4.     class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  5.     <property name="maxUploadSize" value="209715200" />     
  6.     <property name="defaultEncoding" value="UTF-8" />  
  7.     <property name="resolveLazily" value="true" />  
  8. </bean>  

2、在pom.xml中注入上传文件所需的依赖

[html] view plain copy
  1. <!-- 文件上传所依赖的jar包 -->  
  2.     <dependency>  
  3.         <groupId>commons-fileupload</groupId>  
  4.         <artifactId>commons-fileupload</artifactId>  
  5.         <version>1.3.1</version>  
  6.     </dependency>  


3、在项目views文件夹(项目中装页面的文件夹)下新建一个上传单个文件的页面

      @uploadFile.jsp

[html] view plain copy
  1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  7. <title>上传单个文件示例</title>  
  8.   
  9. <link rel="stylesheet" href="<%=request.getContextPath()%>/resources/css/main.css" type="text/css" />  
  10. </head>  
  11. <body>  
  12. <div align="center">  
  13.   
  14. <h1>上传附件</h1>  
  15. <form method="post" action="/HelloSpringMVC/hello/doUpload" enctype="multipart/form-data">  
  16. <input type="file" name="file"/>  
  17. <button type="submit" >提交</button>  
  18. </form>  
  19. </div>  
  20. </body>  
  21. </html>  


   注:
(1)form表单提交的类型一定要加上enctype="multipart/form-data",表示不对所提交的内容编码。
(2)action="" 路径中前面要加项目名,这里项目名是HelloSpringMVC。
(3)doUpload是本表单所提交的对应的处理方法。名为doUpload。

(4)input节点的name="file"中的file与doUpload方法所接收的参数名称一致。

 (5)MultipartFile类常用的一些方法:

String getContentType()//获取文件MIME类型

InputStream getInputStream()//获取文件流

String getName() //获取表单中文件组件的名字

String getOriginalFilename() //获取上传文件的原名

long getSize() //获取文件的字节大小,单位byte

boolean isEmpty() //是否为空

void transferTo(File dest) //保存到一个目标文件中。


4、定义访问成功的页面


@success.jsp

[html] view plain copy
  1. <%@ page language="java" contentType="text/html; charset=UTF-8"  
  2.     pageEncoding="UTF-8"%>  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <link rel="stylesheet" href="<%=request.getContextPath()%>/resources/css/main.css" type="text/css" />  
  7. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  8. <title>上传文件成功页面</title>  
  9. </head>  
  10. <body>  
  11. <div align="center">  
  12. <h1>Success</h1>  
  13. </div>  
  14. </body>  
  15. </html>  

5、在Controller类中加入访问入口方法(就是定位到上传单个文件的页面)


[html] view plain copy
  1. //定位到上传单个文件界面 /hello/upload  
  2.         @RequestMapping(value="/upload"method=RequestMethod.GET)  
  3.         public String showUploadPage(){   
  4.             return "uploadFile";         //view文件夹下的上传单个文件的页面  
  5.         }  

6、在Controller类中定义上传文件的响应方法(就是表单中的所提交的action中的方法名)


[java] view plain copy
  1. /** 
  2.      * 上传单个文件操作 
  3.      * @param RequestParam 括号中的参数名file和表单的input节点的name属性值一致 
  4.      * @return 
  5.      */  
  6.     @RequestMapping(value="/doUpload", method=RequestMethod.POST)  
  7.     public String doUploadFile(@RequestParam("file") MultipartFile file){  
  8.   
  9.         if(!file.isEmpty()){  
  10.             try {  
  11.                   
  12.                 //这里将上传得到的文件保存至 d:\\temp\\file 目录  
  13.                 FileUtils.copyInputStreamToFile(file.getInputStream(), new File("d:\\temp\\file\\",System.currentTimeMillis()+ file.getOriginalFilename()));  
  14.             } catch (IOException e) {  
  15.                 e.printStackTrace();  
  16.             }  
  17.         }  
  18.   
  19.         return "success";  //上传成功则跳转至此success.jsp页面  
  20.     }  

7、运行验证:








二、上传多个文件


步骤如下:

1、2、4步骤同上传单个文件一样,无需重复。


3、在项目views文件夹(项目中装页面的文件夹)下新建一个上传多个文件的页面


@uploadMultifile.jsp


[java] view plain copy
  1. <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  4. <html>  
  5. <head>  
  6. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
  7. <title>上传多个文件示例</title>  
  8.   
  9. <link rel="stylesheet" href="<%=request.getContextPath()%>/resources/css/main.css" type="text/css" />  
  10. </head>  
  11. <body>  
  12. <div align="center">  
  13. <h1>上传多个附件</h1>  
  14. <form method="post" action="/HelloSpringMVC/hello/doMultiUpload" enctype="multipart/form-data">  
  15. <input type="file" name="file1"/>  
  16. <br/>  
  17. <input type="file" name="file2"/>  
  18. <button type="submit" >提交</button>  
  19. </form>  
  20.   
  21. </div>  
  22. </body>  
  23. </html>  

 注:
(1)form表单提交的类型一定要加上enctype="multipart/form-data",表示不对所提交的内容编码。
(2)action="" 路径中前面要加项目名,这里项目名是HelloSpringMVC。
(3)doMultiUpload是本表单所提交的对应的处理方法。名为doMultiUpload。
(4)要传几个文件就加入几个 <input type="file" name="file2"/> 不过name的值要不同


5、在Controller类中加入访问入口方法(就是定位到上传多个文件的页面)


[java] view plain copy
  1. //定位到上传多个文件界面 /hello/uploadMulti  
  2.         @RequestMapping(value="/uploadMulti", method=RequestMethod.GET)  
  3.         public String showUploadPage2(){      
  4.             return "uploadMultifile";        //view文件夹下的上传多个文件的页面  
  5.         }  

6、在Controller类中定义上传文件的响应方法(就是表单中的所提交的action中的方法名)


[java] view plain copy
  1. /** 
  2.          * 上传多个附件的操作类 
  3.          * @param multiRequest 
  4.          * @return 
  5.          * @throws IOException 
  6.          */  
  7.         @RequestMapping(value="/doMultiUpload", method=RequestMethod.POST)  
  8.         public String doUploadFile2(MultipartHttpServletRequest multiRequest) throws IOException{  
  9.   
  10.             Iterator<String> filesNames = multiRequest.getFileNames(); //获得所有的文件名  
  11.             while(filesNames.hasNext()){    //迭代,对单个文件进行操作  
  12.                 String fileName =filesNames.next();  
  13.                 MultipartFile file =  multiRequest.getFile(fileName);  
  14.                 if(!file.isEmpty()){  
  15.                     log.debug("Process file: {}", file.getOriginalFilename());  
  16.                     FileUtils.copyInputStreamToFile(file.getInputStream(), new File("d:\\temp\\imooc\\",System.currentTimeMillis()+ file.getOriginalFilename()));  
  17.                 }  
  18.   
  19.             }  
  20.   
  21.             return "success";  
  22.         }  

注:

1、这里与上传单个文件处理方法不同的是接收参数由MultipartFile类型变为了MultipartHttpServletRequest。

2、MultipartFile由MultipartHttpServletRequest对象的getFile(fileName)方法获得。

/***      * 保存文件      * @param file      * @return      */      private boolean saveFile(MultipartFile file) {          // 判断文件是否为空          if (!file.isEmpty()) {              try {                  // 文件保存路径                  String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"                          + file.getOriginalFilename();                  // 转存文件                  file.transferTo(new File(filePath));                  return true;              } catch (Exception e) {                  e.printStackTrace();              }          }          return false;       }     @RequestMapping("filesUpload")      public String filesUpload(@RequestParam("files") MultipartFile[] files) {          //判断file数组不能为空并且长度大于0          if(files!=null&&files.length>0){              //循环获取file数组中得文件              for(int i = 0;i<files.length;i++){                  MultipartFile file = files[i];if (!file.exists()) { // 判断文件夹是否存在file.mkdirs(); // 不存在则创建}//保存文件 saveFile(file); } } // 重定向 return "redirect:/list.html"; }



原创粉丝点击