`

Spring3 MVC 学习笔记(三)文件上传

阅读更多

spring支持在网络应用程序处理文件上传,提供拔插的org.springframework.web.multipart.MultipartResolver对象 。

在写上传文件的前提下需提供两个jar包:


1.添加上传拦截,可指定上传的大小

 

Java代码  收藏代码
  1. <!-- 上传拦截,如最大上传值及最小上传值 -->  
  2.     <bean id="multipartResolver"  
  3.         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  4.         <!-- one of the properties available; the maximum file size in bytes -->  
  5.         <property name="maxUploadSize" value="100000" />  
  6.     </bean>  

 2.添加java后台处理的API

 

Java代码  收藏代码
  1. @RequestMapping(value = "/form", method = RequestMethod.POST)  
  2. public String handleFormUpload(@RequestParam("name") String name,  
  3. @RequestParam("file") MultipartFile file) {  
  4. if (!file.isEmpty()) {  
  5. byte[] bytes = file.getBytes();  
  6. // 去理上传写文件代码  
  7.   
  8. }  

 

具体文件

    spring_mvc.xml

 

Xml代码  收藏代码
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:p="http://www.springframework.org/schema/p"  
  5.     xmlns:context="http://www.springframework.org/schema/context"  
  6.     xsi:schemaLocation="  
  7.         http://www.springframework.org/schema/beans  
  8.         http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
  9.         http://www.springframework.org/schema/context  
  10.         http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  11.     <!-- 注解资源扫描包路径 -->  
  12.     <context:component-scan base-package="org.spring.mvc" />  
  13.     <bean  
  14.         class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping" />  
  15.   
  16.     <bean  
  17.         class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />  
  18.   
  19.     <!--  对模型视图名称的解析,即在模型视图名称添加前后缀,在requestmapping输入的地址后自动调用该类进行视图解析-->  
  20.     <bean id="viewResolver"  
  21.         class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  22.         <property name="viewClass"  
  23.             value="org.springframework.web.servlet.view.JstlView" />  
  24.         <property name="prefix" value="/" /><!-- 跳转页面的前缀路径 如 /web-inf/user/ -->  
  25.         <property name="suffix" value=".jsp"></property><!-- 跳转页面后缀 如 helloWorld.jsp-->  
  26.     </bean>  
  27.   
  28.     <!-- 上传拦截,如最大上传值及最小上传值 -->  
  29.     <bean id="multipartResolver"  
  30.         class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
  31.         <!-- one of the properties available; the maximum file size in bytes -->  
  32.         <property name="maxUploadSize" value="100000" />  
  33.     </bean>  
  34.   
  35. </beans>  

 

FileUploadController.java文件

 

Java代码  收藏代码
  1. package org.spring.mvc.upload;  
  2.   
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.util.List;  
  7.   
  8. import org.slf4j.Logger;  
  9. import org.slf4j.LoggerFactory;  
  10. import org.spring.mvc.HelloWorldController;  
  11. import org.springframework.stereotype.Controller;  
  12. import org.springframework.web.bind.annotation.RequestMapping;  
  13. import org.springframework.web.bind.annotation.RequestMethod;  
  14. import org.springframework.web.bind.annotation.RequestParam;  
  15. import org.springframework.web.multipart.MultipartFile;  
  16. import org.springframework.web.multipart.MultipartHttpServletRequest;  
  17.   
  18. /** 
  19.  * 上传文件 
  20.  * @author chenyw 
  21.  * 
  22.  */  
  23. @Controller  
  24. @RequestMapping(value = "/toFileUpload")  
  25. public class FileUploadController {  
  26.     private Logger logger = LoggerFactory.getLogger(HelloWorldController.class);  
  27.   
  28.     /** 
  29.      * 单文件上传 
  30.      * @param name @RequestParam 取得name字段的值 
  31.      * @param file 文件 
  32.      * @return 
  33.      * @throws IOException 
  34.      */  
  35.     @RequestMapping(value = "/oneFileUpload", method = RequestMethod.POST)  
  36.     public String handleFormUpload(@RequestParam("name")  
  37.     String name, @RequestParam("file")  
  38.     MultipartFile file) throws IOException {  
  39.           
  40.         logger.info("name:"+name);  
  41.         logger.info("上传文件:"+file.getOriginalFilename());  
  42.         if (!file.isEmpty()) {  
  43.              this.copyFile(file.getInputStream(), file.getOriginalFilename());  
  44.               
  45.         }   
  46.         return "fileUpload/success";  
  47.     }  
  48.   
  49.       /** 
  50.        * 多文件上传 
  51.        * @param request 
  52.        * @param name 
  53.        * @return 
  54.        * @throws Exception 
  55.        */  
  56.       @RequestMapping(value = "/multipartFileUpload",method = RequestMethod.POST)  
  57.          public String upload2(  
  58.             MultipartHttpServletRequest request ,  
  59.             @RequestParam("name") String name    // 页面上的控件值  
  60.             ) throws Exception {  
  61.           List<MultipartFile> files = request.getFiles("file");  
  62.           forint i=0; i<files.size() ;i++){  
  63.                if(! files.get(i).isEmpty()) {  
  64.                    logger.info("上传文件:"+files.get(i).getOriginalFilename());  
  65.                   this.copyFile(files.get(i).getInputStream(), files.get(i).getOriginalFilename());  
  66.                }  
  67.           }  
  68.           logger.info("success");  
  69.           return "fileUpload/success";  
  70.          }  
  71.       
  72.       /** 
  73.        * 写文件到本地 
  74.        * @param in 
  75.        * @param fileName 
  76.        * @throws IOException 
  77.        */  
  78.       private void copyFile(InputStream in,String fileName) throws IOException{  
  79.           FileOutputStream fs = new FileOutputStream("d:/upload/"  
  80.                     + fileName);  
  81.             byte[] buffer = new byte[1024 * 1024];  
  82.             int bytesum = 0;  
  83.             int byteread = 0;  
  84.             while ((byteread = in.read(buffer)) != -1) {  
  85.                 bytesum += byteread;  
  86.                 fs.write(buffer, 0, byteread);  
  87.                 fs.flush();  
  88.             }  
  89.             fs.close();  
  90.             in.close();  
  91.       }  
  92.        
  93.       
  94. }  
 

 

单文件上传页面oneFileUpload.jsp

 

Jsp代码  收藏代码
  1. <%@ page language="java" import="java.util.*" pageEncoding="GBK"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>My JSP 'oneFileUpload.jsp' starting page</title>  
  13.       
  14.     <meta http-equiv="pragma" content="no-cache">  
  15.     <meta http-equiv="cache-control" content="no-cache">  
  16.     <meta http-equiv="expires" content="0">      
  17.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  18.     <meta http-equiv="description" content="This is my page">  
  19.     <!--  
  20.     <link rel="stylesheet" type="text/css" href="styles.css">  
  21.     -->  
  22.   
  23.   </head>  
  24.     
  25.   <body>  
  26.     This is my onefileUpload page. <br>  
  27.     <form method="POST" action="toFileUpload/oneFileUpload" enctype="multipart/form-data">  
  28.         <input type="text" name="name"/>  
  29.         <input type="file" name="file"/>  
  30.         <input type="submit"/>  
  31.     </form>  
  32.   </body>  
  33. </html>  
 

多文件上传页面multipartFileUpload.jsp

 

 

Jsp代码  收藏代码
  1. <%@ page language="java" import="java.util.*" pageEncoding="GBK"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>My JSP 'multipartFileUpload.jsp' starting page</title>  
  13.       
  14.     <meta http-equiv="pragma" content="no-cache">  
  15.     <meta http-equiv="cache-control" content="no-cache">  
  16.     <meta http-equiv="expires" content="0">      
  17.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  18.     <meta http-equiv="description" content="This is my page">  
  19.     <!--  
  20.     <link rel="stylesheet" type="text/css" href="styles.css">  
  21.     -->  
  22.   
  23.   </head>  
  24.     
  25.   <body>  
  26.     This is multipartFileUpload page. <br>  
  27.     <form method="POST" action="toFileUpload/multipartFileUpload" enctype="multipart/form-data">  
  28.         <input type="text" name="name"/><br>  
  29.         <input type="file" name="file"/><br>  
  30.         <input type="file" name="file"/><br>  
  31.         <input type="submit"/><br>  
  32.     </form>  
  33.   </body>  
  34. </html>  
 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics