SpringMVC基础-09-文件上传(单文件、多文件上传)

代码示例

FileUploadController.java:

 1 package com.atguigu.controller;
 2 
 3 import org.springframework.stereotype.Controller;
 4 import org.springframework.ui.Model;
 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 import java.io.File;
10 import java.io.IOException;
11 
12 /**
13  * @Title: FileUploadController
14  * @Description:
15  * @Author:
16  * @Version: 1.0
17  * @create 2020/6/22 10:28
18  */
19 @Controller
20 public class FileUploadController {
21 
22     /**
23      * @Description: 单文件上传
24      * @Param: [username, file, model]
25      * @Return: java.lang.String
26      * @Author:
27      * @Date: 2020/6/22 10:49
28      */
29 /*    @RequestMapping("/upload")
30     public String upload(@RequestParam(value = "username", required = false) String username,
31                          @RequestParam("headerimg") MultipartFile file,
32                          Model model) {
33         System.out.println("上传的文件信息");
34         System.out.println("文件项的name" + file.getName());//headerimg
35         System.out.println("文件的名字" + file.getOriginalFilename());
36 
37         //文件保存
38         try {
39             file.transferTo(new File("E:\upload\" + file.getOriginalFilename()));
40             model.addAttribute("msg", "文件上传成功");
41         } catch (IOException e) {
42             model.addAttribute("msg", "文件上传失败" + e.getMessage());
43         }
44         return "forward:/index.jsp";
45     }*/
46 
47     /**
48      * @Description: 多文件上传
49      * @Param: [username, file, model]
50      * @Return: java.lang.String
51      * @Author:
52      * @Date: 2020/6/22 10:49
53      */
54     @RequestMapping("/upload")
55     public String upload(@RequestParam(value = "username", required = false) String username,
56                          @RequestParam("headerimg") MultipartFile[] file,
57                          Model model) {
58 
59         for (MultipartFile multipartFile : file) {
60             if(!multipartFile.isEmpty()){
61                 System.out.println("上传的文件信息");
62                 System.out.println("文件项的name" + multipartFile.getName());//headerimg
63                 System.out.println("文件的名字" + multipartFile.getOriginalFilename());
64                 try {
65                     multipartFile.transferTo(new File("E:\upload\" + multipartFile.getOriginalFilename()));
66                     model.addAttribute("msg", "文件上传成功");
67                 } catch (IOException e) {
68                     model.addAttribute("msg", "文件上传失败" + e.getMessage());
69                 }
70             }
71         }
72         return "forward:/index.jsp";
73     }
74 }

springmvc.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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
 7         http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
 8         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
 9 
10     <context:component-scan base-package="com.atguigu"></context:component-scan>
11     
12     <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
13         <property name="prefix" value="/WEB-INF/pages/"></property>
14         <property name="suffix" value=".jsp"></property>
15     </bean>
16 
17     <!-- 默认前端控制器是拦截所有资源(除过jsp),js文件就404了;要js文件的请求是交给tomcat处理的
18     http://localhost:8080/7.SpringMVC_crud/scripts/jquery-1.9.1.min.js -->
19     <!-- 告诉SpringMVC,自己映射的请求就自己处理,不能处理的请求直接交给tomcat -->
20     <!-- 静态资源能访问,动态映射的请求就不行 -->
21     <mvc:default-servlet-handler/>
22     <!-- springmvc可以保证动态请求和静态请求都能访问 -->
23     <mvc:annotation-driven/>
24 
25     <!--配置文件上传解析器 id必须是multipartResolver-->
26     <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
27         <!--最大20M-->
28         <property name="maxUploadSize" value="#{1024*1024*20}"></property>
29         <!--设置默认的编码-->
30         <property name="defaultEncoding" value="utf-8"></property>
31 
32     </bean>
33 
34 </beans>

web.xml:

 1 <!DOCTYPE web-app PUBLIC
 2         "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 3         "http://java.sun.com/dtd/web-app_2_3.dtd" >
 4 
 5 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
 6          xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
 7          id="WebApp_ID" version="3.0">
 8     <display-name>9.SpringMVC_upload</display-name>
 9     <welcome-file-list>
10         <welcome-file>index.jsp</welcome-file>
11     </welcome-file-list>
12 
13     <!-- The front controller of this Spring Web application,
14     responsible for handling all application requests -->
15     <servlet>
16         <servlet-name>springDispatcherServlet</servlet-name>
17         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
18         <init-param>
19             <!-- contextConfigLocation:指定SpringMVC配置文件位置 -->
20             <param-name>contextConfigLocation</param-name>
21             <param-value>classpath:springmvc.xml</param-value>
22         </init-param>
23         <load-on-startup>1</load-on-startup>
24     </servlet>
25 
26     <!-- Map all requests to the DispatcherServlet for handling -->
27     <servlet-mapping>
28         <servlet-name>springDispatcherServlet</servlet-name>
29         <url-pattern>/</url-pattern>
30     </servlet-mapping>
31 
32     <!-- 配置一个字符编码的Filter;一定注意:字符编码filter一般都在其他Filter之前; -->
33     <!--配置字符集编码的Filter-->
34     <filter>
35         <filter-name>CharacterEncodingFilter</filter-name>
36         <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
37         <!-- encoding:指定解决POST请求乱码 -->
38         <init-param>
39             <param-name>encoding</param-name>
40             <!--不区分大小写-->
41             <param-value>utf-8</param-value>
42         </init-param>
43         <init-param>
44             <!-- forceEncoding:顺手解决响应乱码;response.setCharacterEncoding(this.encoding); -->
45             <param-name>forceEncoding</param-name>
46             <param-value>true</param-value>
47         </init-param>
48     </filter>
49     <filter-mapping>
50         <filter-name>CharacterEncodingFilter</filter-name>
51         <url-pattern>/*</url-pattern>
52     </filter-mapping>
53 
54     <!--支持Rest风格的Filter(开启PUT、DELETE请求)-->
55     <filter>
56         <filter-name>HiddenHttpMethodFilter</filter-name>
57         <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
58     </filter>
59     <filter-mapping>
60         <filter-name>HiddenHttpMethodFilter</filter-name>
61         <url-pattern>/*</url-pattern>
62     </filter-mapping>
63     <!-- 使用SpringMVC前端控制器写完就直接写字符编码过滤器;
64         Tomcat一装上,上手就是server.xml的8080处添加URIEncoding="UTF-8"
65      -->
66 
67 </web-app>

index.jsp:

 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     <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7     <title>Insert title here</title>
 8     <%
 9         pageContext.setAttribute("ctp", request.getContextPath());
10     %>
11 </head>
12 <body>
13 <!--
14     1.文件上传
15         1)文件上传表单准备:enctype="multipart/form-data"
16         2)导入fileupload jar包:
17             commons-fileupload
18             commons-io
19         3)只要在SpringMVC配置文件中编写一个配置,配置文件上传解析器 MultipartResolver
20         4)文件上传请求处理
21             在处理器方法上写一个@RequestParam("headerimg") MultipartFile file,封装当前文件的信息,可以直接保存
22 
23 -->
24 ${msg}
25 <form action="${ctp}/upload" method="post"enctype="multipart/form-data">
26     用户头像:<input type="file"name="headerimg"><br/>
27     用户头像:<input type="file" name="headerimg"><br/>
28     用户头像:<input type="file" name="headerimg"><br/>
29     用户头像:<input type="file" name="headerimg"><br/>
30     用户头像:<input type="file" name="headerimg"><br/>
31     用户名:<input type="text" name="username"><br/>
32     <input type="submit" value="提交">
33 </form>
34 </body>
35 </html>
原文地址:https://www.cnblogs.com/116970u/p/13177689.html