SpringMVC实现文件上传

简介:

文件上传是Web开发中的一个重要的功能点。同样,SpringMVC也可以通过简单的配置就可以实现文件的上传以及对上传的文件的处理。具体步骤如下:

一 新建测试项目以及导入jar包

详细过程不用多说,项目结构和需要的jar包如下:

wKioL1czUcugStDUAABcOr_ekYE451.png  wKiom1czUPmx247vAAAjAnTdSKM217.png

二 项目的常规配置以及实现上传需要的配置

(1)web.xml:

在这里只用了简单的常规配置,不用多说:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
< web-app  xmlns = "http://xmlns.jcp.org/xml/ns/javaee"
          xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
          xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
       http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
          version = "3.1" >
 
     < servlet >
         < servlet-name >springmvc</ servlet-name >
         < servlet-class >org.springframework.web.servlet.DispatcherServlet</ servlet-class >
         < load-on-startup >1</ load-on-startup >
     </ servlet >
 
     < servlet-mapping >
         < servlet-name >springmvc</ servlet-name >
         < url-pattern >*.html</ url-pattern >
     </ servlet-mapping >
     
     < filter >
         < filter-name >characterEncodingFilter</ filter-name >
         < filter-class >org.springframework.web.filter.CharacterEncodingFilter</ filter-class >
         < init-param >
             < param-name >encoding</ param-name >
             < param-value >UTF-8</ param-value >
         </ init-param >
     </ filter >
     < filter-mapping >
         < filter-name >characterEncodingFilter</ filter-name >
         < url-pattern >/*</ url-pattern >
     </ filter-mapping >
 
</ web-app >

(2)springmvc-servlet.xml:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<? xml  version = "1.0"  encoding = "UTF-8" ?>
< beans  xmlns = "http://www.springframework.org/schema/beans"
     xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"  xmlns:context = "http://www.springframework.org/schema/context"
     xmlns:mvc = "http://www.springframework.org/schema/mvc"
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
                             http://www.springframework.org/schema/beans/spring-beans-4.0.xsd 
                             http://www.springframework.org/schema/context
                             http://www.springframework.org/schema/context/spring-context-4.0.xsd
                             http://www.springframework.org/schema/mvc 
                             http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
 
     < context:component-scan  base-package = "cn.zifangsky.* *.controller"  />
 
     < context:annotation-config  />   <!-- 激活Bean中定义的注解 -->
     < mvc:annotation-driven  />
 
     <!-- 视图相关配置 -->
     < bean
         class = "org.springframework.web.servlet.view.InternalResourceViewResolver" >
         < property  name = "prefix"  value = "/WEB-INF/pages/"  />   <!-- 视图前缀 -->
         < property  name = "suffix"  value = ".jsp"  />   <!-- 视图后缀 -->
     </ bean >
 
     < bean  id = "multipartResolver"  class = "org.springframework.web.multipart.commons.CommonsMultipartResolver" >
         < property  name = "uploadTempDir"  value = "/tmp"  />   <!-- 临时目录 -->
         < property  name = "maxUploadSize"  value = "10485760" />  <!-- 10M -->
     </ bean >
</ beans >

在上面的代码中的最后一段,配置了一个名为”multipartResolver“的bean,这里就是配置了Commons FileUpload来处理文件上传

三 文件上传处理流程

(1)首页index.jsp:

1
<% response.sendRedirect("form.html"); %>

(2)模型类User.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package  cn.zifangsky.model;
 
public  class  User {
     private  String userName;  // 用户名
     private  String logoSrc;  // 头像地址
 
     public  String getUserName() {
         return  userName;
     }
 
     public  void  setUserName(String userName) {
         this .userName = userName;
     }
 
     public  String getLogoSrc() {
         return  logoSrc;
     }
 
     public  void  setLogoSrc(String logoSrc) {
         this .logoSrc = logoSrc;
     }
 
}

(3)文件上传表单和结果展示页fileupload.jsp:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<%@ page language="java" contentType="text/html; charset=UTF-8"
     pageEncoding="UTF-8"%>
<%@taglib prefix="mvc" uri="http://www.springframework.org/tags/form"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
< html >
< head >
< title >Spring MVC文件上传</ title >
</ head >
< body >
     < h2 >图片文件上传</ h2 >
     < mvc:form  modelAttribute = "user"  action = "upload.html"
         enctype = "multipart/form-data" >
         < table >
             < tr >
                 < td >用户名:</ td >
                 < td >< mvc:input  path = "userName"  /></ td >
             </ tr >
             < tr >
                 < td >选择头像:</ td >
                 < td >< input  type = "file"  name = "file"  /></ td >
             </ tr >
             < tr >
                 < td  colspan = "2" >< input  type = "submit"  value = "Submit"  /></ td >
             </ tr >
         </ table >
     </ mvc:form >
     < br >< br >
     < c:if  test = "${u !=null }" >
         < h2 >上传结果</ h2 >
         < table >
             < c:if  test = "${u.userName != null }" >
                 < tr >
                     < td >用户名:</ td >
                     < td >${u.userName}</ td >
                 </ tr >
             </ c:if >
             < c:if  test = "${u.logoSrc != null }" >
                 < tr >
                     < td >头像:</ td >
                     < td >< img  src = "${u.logoSrc}"  width = "100px"  height = "100px" ></ td >
                 </ tr >
             </ c:if >
             
         </ table >
 
     </ c:if >
 
</ body >
</ html >

可以看出,在上面的form表单中定义的是文件上传表单,同时为了能够上传文件,添加了一个enctype=”multipart/form-data”属性。后面就是结果展示页了,使用JSTL标签来判断是否有结果,有的话就显示出来

(4)后台处理UploadController.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package  cn.zifangsky.controller;
 
import  java.io.File;
import  java.io.IOException;
 
import  javax.servlet.http.HttpServletRequest;
 
import  org.apache.commons.io.FileUtils;
import  org.springframework.stereotype.Controller;
import  org.springframework.web.bind.annotation.RequestMapping;
import  org.springframework.web.bind.annotation.RequestMethod;
import  org.springframework.web.bind.annotation.RequestParam;
import  org.springframework.web.multipart.MultipartFile;
import  org.springframework.web.servlet.ModelAndView;
 
import  cn.zifangsky.model.User;
import  cn.zifangsky.utils.StringUtile;
 
@Controller
public  class  UploadController {
 
     @RequestMapping (value =  "/form" )
     public  ModelAndView form() {
         ModelAndView modelAndView =  new  ModelAndView( "fileupload" "user" new  User());
 
         return  modelAndView;
     }
 
     @RequestMapping (value =  "/upload" , method = RequestMethod.POST)
     public  ModelAndView upload(User user,  @RequestParam ( "file" ) MultipartFile tmpFile, HttpServletRequest request) {
         ModelAndView modelAndView =  new  ModelAndView( "fileupload" );
 
         if  (tmpFile !=  null ) {
             // 获取物理路径
             String targetDirectory = request.getSession().getServletContext().getRealPath( "/uploads" );
             String tmpFileName = tmpFile.getOriginalFilename();  // 上传的文件名
             int  dot = tmpFileName.lastIndexOf( '.' );
             String ext =  "" ;   //文件后缀名
             if  ((dot > - 1 ) && (dot < (tmpFileName.length() -  1 ))) {
                 ext = tmpFileName.substring(dot +  1 );
             }
             // 其他文件格式不处理
             if  ( "png" .equalsIgnoreCase(ext) ||  "jpg" .equalsIgnoreCase(ext) ||  "gif" .equalsIgnoreCase(ext)) {
                 // 重命名上传的文件名
                 String targetFileName = StringUtile.renameFileName(tmpFileName);
                 // 保存的新文件
                 File target =  new  File(targetDirectory, targetFileName);
 
                 try  {
                     // 保存文件
                     FileUtils.copyInputStreamToFile(tmpFile.getInputStream(), target);
                 catch  (IOException e) {
                     e.printStackTrace();
                 }
 
                 User u =  new  User();
                 u.setUserName(user.getUserName());
                 u.setLogoSrc(request.getContextPath() +  "/uploads/"  + targetFileName);
 
                 modelAndView.addObject( "u" , u);
             }
 
             return  modelAndView;
         }
 
         return  modelAndView;
     }
 
}

在上面的upload方法中,为了接收上传的文件,因此使用了一个MultipartFile类型的变量来接收上传的临时文件,同时为了给文件进行重命名,我调用了一个renameFileName方法,这个方法的具体内容如下:

1
2
3
4
5
6
7
8
9
10
/**
      * 文件重命名
      */
     public  static  String renameFileName(String fileName) {
         String formatDate =  new  SimpleDateFormat( "yyMMddHHmmss" ).format( new  Date());  // 当前时间字符串
         int  random =  new  Random().nextInt( 10000 );
         String extension = fileName.substring(fileName.lastIndexOf( "." ));  // 文件后缀
 
         return  formatDate + random + extension;
     }

至此,全部处理逻辑已经完成。

四 效果测试

(1)文件上传表单:

wKioL1czUnnCoqOJAAAm1WoJkvo269.png

(2)上传结果:

wKioL1czUpGSActAAAA_-proDt0609.png



本文转自 pangfc 51CTO博客,原文链接:http://blog.51cto.com/983836259/1772440,如需转载请自行联系原作者

相关文章
|
前端开发 Java 测试技术
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestParam
本文介绍了 `@RequestParam` 注解的使用方法及其与 `@PathVariable` 的区别。`@RequestParam` 用于从请求中获取参数值(如 GET 请求的 URL 参数或 POST 请求的表单数据),而 `@PathVariable` 用于从 URL 模板中提取参数。文章通过示例代码详细说明了 `@RequestParam` 的常用属性,如 `required` 和 `defaultValue`,并展示了如何用实体类封装大量表单参数以简化处理流程。最后,结合 Postman 测试工具验证了接口的功能。
981 0
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestParam
|
11月前
|
前端开发 Java 微服务
《深入理解Spring》:Spring、Spring MVC与Spring Boot的深度解析
Spring Framework是Java生态的基石,提供IoC、AOP等核心功能;Spring MVC基于其构建,实现Web层MVC架构;Spring Boot则通过自动配置和内嵌服务器,极大简化了开发与部署。三者层层演进,Spring Boot并非替代,而是对前者的高效封装与增强,适用于微服务与快速开发,而深入理解Spring Framework有助于更好驾驭整体技术栈。
|
JSON 前端开发 Java
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestBody
`@RequestBody` 是 Spring 框架中的注解,用于将 HTTP 请求体中的 JSON 数据自动映射为 Java 对象。例如,前端通过 POST 请求发送包含 `username` 和 `password` 的 JSON 数据,后端可通过带有 `@RequestBody` 注解的方法参数接收并处理。此注解适用于传递复杂对象的场景,简化了数据解析过程。与表单提交不同,它主要用于接收 JSON 格式的实体数据。
1675 0
|
前端开发 Java 微服务
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@PathVariable
`@PathVariable` 是 Spring Boot 中用于从 URL 中提取参数的注解,支持 RESTful 风格接口开发。例如,通过 `@GetMapping(&quot;/user/{id}&quot;)` 可以将 URL 中的 `{id}` 参数自动映射到方法参数中。若参数名不一致,可通过 `@PathVariable(&quot;自定义名&quot;)` 指定绑定关系。此外,还支持多参数占位符,如 `/user/{id}/{name}`,分别映射到方法中的多个参数。运行项目后,访问指定 URL 即可验证参数是否正确接收。
1055 0
|
JSON 前端开发 Java
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RequestMapping
@RequestMapping 是 Spring MVC 中用于请求地址映射的注解,可作用于类或方法上。类级别定义控制器父路径,方法级别进一步指定处理逻辑。常用属性包括 value(请求地址)、method(请求类型,如 GET/POST 等,默认 GET)和 produces(返回内容类型)。例如:`@RequestMapping(value = &quot;/test&quot;, produces = &quot;application/json; charset=UTF-8&quot;)`。此外,针对不同请求方式还有简化注解,如 @GetMapping、@PostMapping 等。
1025 0
|
JSON 前端开发 Java
微服务——SpringBoot使用归纳——Spring Boot中的MVC支持——@RestController
本文主要介绍 Spring Boot 中 MVC 开发常用的几个注解及其使用方式,包括 `@RestController`、`@RequestMapping`、`@PathVariable`、`@RequestParam` 和 `@RequestBody`。其中重点讲解了 `@RestController` 注解的构成与特点:它是 `@Controller` 和 `@ResponseBody` 的结合体,适用于返回 JSON 数据的场景。文章还指出,在需要模板渲染(如 Thymeleaf)而非前后端分离的情况下,应使用 `@Controller` 而非 `@RestController`
661 0
|
前端开发 Java API
Spring Cloud Gateway Server Web MVC报错“Unsupported transfer encoding: chunked”解决
本文解析了Spring Cloud Gateway中出现“Unsupported transfer encoding: chunked”错误的原因,指出该问题源于Feign依赖的HTTP客户端与服务端的`chunked`传输编码不兼容,并提供了具体的解决方案。通过规范Feign客户端接口的返回类型,可有效避免该异常,提升系统兼容性与稳定性。
920 0
|
SQL Java 数据库连接
Spring、SpringMVC 与 MyBatis 核心知识点解析
我梳理的这些内容,涵盖了 Spring、SpringMVC 和 MyBatis 的核心知识点。 在 Spring 中,我了解到 IOC 是控制反转,把对象控制权交容器;DI 是依赖注入,有三种实现方式。Bean 有五种作用域,单例 bean 的线程安全问题及自动装配方式也清晰了。事务基于数据库和 AOP,有失效场景和七种传播行为。AOP 是面向切面编程,动态代理有 JDK 和 CGLIB 两种。 SpringMVC 的 11 步执行流程我烂熟于心,还有那些常用注解的用法。 MyBatis 里,#{} 和 ${} 的区别很关键,获取主键、处理字段与属性名不匹配的方法也掌握了。多表查询、动态
403 0
|
JSON 前端开发 Java
第05课:Spring Boot中的MVC支持
第05课:Spring Boot中的MVC支持
480 0
|
SQL Java 数据库连接
对Spring、SpringMVC、MyBatis框架的介绍与解释
Spring 框架提供了全面的基础设施支持,Spring MVC 专注于 Web 层的开发,而 MyBatis 则是一个高效的持久层框架。这三个框架结合使用,可以显著提升 Java 企业级应用的开发效率和质量。通过理解它们的核心特性和使用方法,开发者可以更好地构建和维护复杂的应用程序。
1060 29