springmvc-文件上传

导入maven依赖

 1 <dependencies>
 2         <!--文件上传-->
 3         <dependency>
 4             <groupId>commons-fileupload</groupId>
 5             <artifactId>commons-fileupload</artifactId>
 6             <version>1.3.3</version>
 7         </dependency>
 8         <!--servlet-api 导入高版本-->
 9         <dependency>
10             <groupId>javax.servlet</groupId>
11             <artifactId>javax.servlet-api</artifactId>
12             <version>4.0.1</version>
13         </dependency>
14     </dependencies>

配置web.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
 3          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4          xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
 5          version="4.0">
 6 
 7     <servlet>
 8         <servlet-name>DispatcherServlet</servlet-name>
 9         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
10         <init-param>
11             <param-name>contextConfigLocation</param-name>
12             <param-value>classpath:applicationContext.xml</param-value>
13         </init-param>
14         <load-on-startup>1</load-on-startup>
15     </servlet>
16 
17     <servlet-mapping>
18         <servlet-name>DispatcherServlet</servlet-name>
19         <url-pattern>/</url-pattern>
20     </servlet-mapping>
21 
22 
23     <!--防止中文乱码-->
24     <filter>
25         <filter-name>encoding</filter-name>
26         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
27         <init-param>
28             <param-name>encoding</param-name>
29             <param-value>UTF-8</param-value>
30         </init-param>
31     </filter>
32     <filter-mapping>
33         <filter-name>encoding</filter-name>
34         <url-pattern>/*</url-pattern>
35     </filter-mapping>
36 </web-app>

在src下的resources下建applicationContext.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:context="http://www.springframework.org/schema/context"
 5        xmlns:mvc="http://www.springframework.org/schema/mvc"
 6        xsi:schemaLocation="http://www.springframework.org/schema/beans
 7        http://www.springframework.org/schema/beans/spring-beans.xsd
 8        http://www.springframework.org/schema/context
 9        http://www.springframework.org/schema/context/spring-context.xsd
10        http://www.springframework.org/schema/mvc
11        http://www.springframework.org/schema/mvc/spring-mvc.xsd">
12     <!--自动扫描包,下面注解类交给iod容器处理-->
13     <context:component-scan base-package="com.rzk.controller"/>
14     <!--静态资源过滤-->
15     <mvc:default-servlet-handler/>
16     <!--注解驱动-->
17     <mvc:annotation-driven/>
18     <!--JSON乱码问题配置-->
19     <mvc:annotation-driven>
20         <mvc:message-converters>
21             <bean class="org.springframework.http.converter.StringHttpMessageConverter">
22                 <constructor-arg value="UTF-8"/>
23             </bean>
24             <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
25                 <property name="objectMapper">
26                     <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
27                         <property name="failOnEmptyBeans" value="false"/>
28                     </bean>
29                 </property>
30             </bean>
31         </mvc:message-converters>
32     </mvc:annotation-driven>
33 
34 
35     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
36         <property name="prefix" value="/WEB-INF/jsp/"/>
37         <property name="suffix" value=".jsp"/>
38     </bean>
39 
40     <!--文件上传配置-->
41     <bean id="multipartResolver"  class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
42         <!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
43         <property name="defaultEncoding" value="utf-8"/>
44         <!-- 上传文件大小上限,单位为字节(10485760=10M) -->
45         <property name="maxUploadSize" value="10485760"/>
46         <property name="maxInMemorySize" value="40960"/>
47     </bean>
48 
49 </beans>

新建上传页面

1   <form action="${pageContext.request.contextPath}/file/upload" method="post" enctype="multipart/form-data">
2       <input type="file" name="file">
3     <input type="submit" value="upload">
4   </form>

controller

 1 @Controller
 2 @RequestMapping("/file")
 3 public class FileController {
 4     //@RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象
 5     //批量上传CommonsMultipartFile则为数组即可
 6     @RequestMapping("/upload")
 7     public String fileUpload(@RequestParam("file") CommonsMultipartFile file , HttpServletRequest request) throws IOException {
 8 
 9         //获取文件名 : file.getOriginalFilename();
10         String uploadFileName = file.getOriginalFilename();
11 
12         //如果文件名为空,直接回到首页!
13         if ("".equals(uploadFileName)){
14             return "redirect:/index.jsp";
15         }
16         System.out.println("上传文件名 : "+uploadFileName);
17 
18         //上传路径保存设置
19         String path = request.getServletContext().getRealPath("/upload");
20         //如果路径不存在,创建一个
21         File realPath = new File(path);
22         if (!realPath.exists()){
23             realPath.mkdir();
24         }
25         System.out.println("上传文件保存地址:"+realPath);
26 
27         InputStream is = file.getInputStream(); //文件输入流
28         OutputStream os = new FileOutputStream(new File(realPath,uploadFileName)); //文件输出流
29 
30         //读取写出
31         int len=0;
32         byte[] buffer = new byte[1024];
33         while ((len=is.read(buffer))!=-1){
34             os.write(buffer,0,len);
35             os.flush();
36         }
37         os.close();
38         is.close();
39         return "redirect:/index.jsp";
40     }
41 }

controller第二种上传方式

 1    @RequestMapping("/upload2")
 2     public String  fileUpload2(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
 3 
 4         //上传路径保存设置
 5         String path = request.getServletContext().getRealPath("/upload");
 6         File realPath = new File(path);
 7         if (!realPath.exists()){
 8             realPath.mkdir();
 9         }
10         //上传文件地址
11         System.out.println("上传文件保存地址:"+realPath);
12 
13         //通过CommonsMultipartFile的方法直接写文件(注意这个时候)
14         file.transferTo(new File(realPath +"/"+ file.getOriginalFilename()));
15 
16         return "redirect:/index.jsp";
17     }

 

上一篇:文件上传与下载


下一篇:文件上传和下载