Spring MVC单文件上传(附带实例)

朱雀 2020-02-02 06:20 2586阅读 0赞

Spring MVC单文件上传(附带实例)

本节通过一个应用案例 springMVCDemo11 讲解 Spring MVC 框架如何实现单文件上传,具体步骤如下:

1)创建应用并导入 JAR 包

创建应用 springMVCDemo11,将 Spring MVC 相关的 JAR 包、commons-fileupload 组件相关的 JAR 包以及 JSTL 相关的 JAR 包导入应用的 lib 目录中,如图 1 所示。

springMVCDemo11应用的JAR包
图 1 springMVCDemo11

2)创建 web.xml 文件

在 WEB-INF 目录下创建 web.xml 文件。为防止中文乱码,需要在 web.xml 文件中添加字符编码过滤器,这里不再赘述。

3)创建文件选择页面

在 WebContent 目录下创建 JSP 页面 oneFile.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. </head>
  9. <body>
  10. <form action="${pageContext.request.contextPath }/onefile"
  11. method="post" enctype="multipart/form-data">
  12. 选择文件:<input type="file" name="myfile"><br>
  13. 文件描述:<input type="text" name="description"><br>
  14. <input type="submit" value="提交">
  15. </form>
  16. </body>
  17. </html>

4)创建 POJO 类

在 src 目录下创建 pojo 包,在该包中创建 POJO 类 FileDomain。然后在该 POJO 类中声明一个 MultipartFile 类型的属性封装被上传的文件信息,属性名与文件选择页面 oneFile.jsp 中的 file 类型的表单参数名 myfile 相同。具体代码如下:

  1. package pojo;
  2. import org.springframework.web.multipart.MultipartFile;
  3. public class FileDomain {
  4. private String description;
  5. private MultipartFile myfile;
  6. public String getDescription() {
  7. return description;
  8. }
  9. public void setDescription(String description) {
  10. this.description = description;
  11. }
  12. public MultipartFile getMyfile() {
  13. return myfile;
  14. }
  15. public void setMyfile(MultipartFile myfile) {
  16. this.myfile = myfile;
  17. }
  18. }

5)创建控制器类

在 src 目录下创建 controller 包,并在该包中创建 FileUploadController 控制器类。具体代码如下:

  1. kage controller;
  2. import java.io.File;
  3. import javax.servlet.http.HttpServletRequest;
  4. import org.apache.commons.logging.Log;
  5. import org.apache.commons.logging.LogFactory;
  6. import org.springframework.stereotype.Controller;
  7. import org.springframework.web.bind.annotation.ModelAttribute;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import pojo.FileDomain;
  10. @Controller
  11. public class FileUploadController {
  12. // 得到一个用来记录日志的对象,这样在打印信息时能够标记打印的是哪个类的信息
  13. private static final Log logger = LogFactory.getLog(FileUploadController.class);
  14. /**
  15. * 单文件上传
  16. */
  17. @RequestMapping("/onefile")
  18. public String oneFileUpload(@ModelAttribute FileDomain fileDomain,
  19. HttpServletRequest request) {
  20. /*
  21. * 文件上传到服务器的位置“/uploadfiles”,该位置是指
  22. * workspace\.metadata\.plugins\org.eclipse
  23. * .wst.server.core\tmp0\wtpwebapps, 发布后使用
  24. */
  25. String realpath = request.getServletContext()
  26. .getRealPath("uploadfiles");
  27. String fileName = fileDomain.getMyfile().getOriginalFilename();
  28. File targetFile = new File(realpath, fileName);
  29. if (!targetFile.exists()) {
  30. targetFile.mkdirs();
  31. }
  32. // 上传
  33. try {
  34. fileDomain.getMyfile().transferTo(targetFile);
  35. logger.info("成功");
  36. } catch (Exception e) {
  37. e.printStackTrace();
  38. }
  39. return "showOne";
  40. }
  41. }

6)创建 Spring MVC 的配置文件

在上传文件时需要在配置文件中使用 Spring 的 CommonsMultipartResolver 类配置 MultipartResolver 用于文件上传,应用的配置文件 springmvc-servlet.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:mvc="http://www.springframework.org/schema/mvc"
  5. xmlns:p="http://www.springframework.org/schema/p"
  6. xmlns:context="http://www.springframework.org/schema/context"
  7. xsi:schemaLocation="
  8. http://www.springframework.org/schema/beans
  9. http://www.springframework.org/schema/beans/spring-beans.xsd
  10. http://www.springframework.org/schema/context
  11. http://www.springframework.org/schema/context/spring-context.xsd
  12. http://www.springframework.org/schema/mvc
  13. http://www.springframework.org/schema/mvc/spring-mvc.xsd">
  14. <!-- 使用扫描机制扫描包 -->
  15. <context:component-scan base-package="controller" />
  16. <!-- 完成视图的对应 -->
  17. <!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 -->
  18. <bean
  19. class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  20. <property name="prefix" value="/WEB-INF/jsp/" />
  21. <property name="suffix" value=".jsp" />
  22. </bean>
  23. <!-- 配置MultipartResolver,用于上传文件,使用spring的CommonsMultipartResolver -->
  24. <bean id="multipartResolver"
  25. class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  26. <property name="maxUploadSize" value="5000000" />
  27. <property name="defaultEncoding" value="UTF-8" />
  28. </bean>
  29. </beans>

7)创建成功显示页面

在 WEB-INF 目录下创建 JSP 文件夹,并在该文件夹中创建单文件上传成功显示页面 showOne.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. </head>
  9. <body>
  10. ${fileDomain.description }
  11. <br>
  12. <!-- fileDomain.getMyFile().getOriginalFilename()-->
  13. ${fileDomain.myfile.originalFilename }
  14. </body>
  15. </html>

8)测试文件上传

发布 springMVCDemo11 应用到 Tomcat 服务器并启动 Tomcat 服务器,然后通过地址“http://localhost:8080/springMVCDemo11/oneFile.jsp”运行文件选择页面,运行结果如图 2 所示。

单文件选择页面
图 2 单文件选择页面

在图 2 中选择文件并输入文件描述,然后单击“提交”按钮上传文件,若成功则显示如图 3 所示的结果。

单文件成功上传结果
图 3 单文件成功上传结果

发表评论

表情:
评论列表 (有 0 条评论,2586人围观)

还没有评论,来说两句吧...

相关阅读

    相关 spring mvc-文件

                在文件上传时,我们需要用到文件上传解析器,其实,它并不陌生,只是对httpServletRequest的一个扩展,使其能够更好的处理文件上传,扩展的接口