Spring MVC文件上传处理
以下示例显示如何在使用Spring Web MVC框架的表单中上传文件和处理。首先使用Eclipse IDE来创建一个WEB工程,实现一个上传文件并保存的功能。并按照以下步骤使用Spring Web Framework开发基于动态表单的Web应用程序:
- 创建一个名称为 FileUpload 的动态WEB项目。
- 在 com.yiibai.springmvc包下创建两个Java类FileModel,FileUploadController。
- 在jsp子文件夹下创建两个视图文件:fileUpload.jsp和success.jsp。
- 在WebContent文件夹下创建一个文件夹:temp。
- 下载Apache Commons FileUpload库:commons-fileupload.jar和Apache Commons IO库:commons-io.jar。把它们放在CLASSPATH中。
- 最后一步是创建所有源和配置文件的内容并运行应用程序,详细如下所述。
完整的项目文件目录结构如下所示 -

FileModel.java 的代码如下所示 -
package com.yiibai.springmvc;
import org.springframework.web.multipart.MultipartFile;
public class FileModel {
   private MultipartFile file;
   public MultipartFile getFile() {
      return file;
   }
   public void setFile(MultipartFile file) {
      this.file = file;
   }
}
FileUploadController.java 的代码如下所示 -
package com.yiibai.springmvc;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class FileUploadController {
   @Autowired
   ServletContext context; 
   @RequestMapping(value = "/fileUploadPage", method = RequestMethod.GET)
   public ModelAndView fileUploadPage() {
      FileModel file = new FileModel();
      ModelAndView modelAndView = new ModelAndView("fileUpload", "command", file);
      return modelAndView;
   }
   @RequestMapping(value="/fileUploadPage", method = RequestMethod.POST)
   public String fileUpload(@Validated FileModel file, BindingResult result, ModelMap model) throws IOException {
      if (result.hasErrors()) {
         System.out.println("validation errors");
         return "fileUploadPage";
      } else {
         System.out.println("Fetching file");
         MultipartFile multipartFile = file.getFile();
         String uploadPath = context.getRealPath("") + File.separator + "temp" + File.separator;
         //Now do something with file...
         FileCopyUtils.copy(file.getFile().getBytes(), new File(uploadPath+file.getFile().getOriginalFilename()));
         String fileName = multipartFile.getOriginalFilename();
         model.addAttribute("fileName", fileName);
         return "success";
      }
   }
}
FileUpload-servlet.xml 的代码如下所示 -
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="
   http://www.springframework.org/schema/beans
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
   http://www.springframework.org/schema/context
   http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <context:component-scan base-package="com.yiibai.springmvc" />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/" />
        <property name="suffix" value=".jsp" />
    </bean>
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver" />
</beans>
这里的第一个服务方法fileUploadPage(),我们已经在名为“command”的ModelAndView对象中传递了一个空的FileModel对象,因为如果JSP文件中使用<form:form>标签,spring框架期望一个名称为“command”的对象。 因此,当调用fileUploadPage()方法时,它返回fileUpload.jsp视图。
第二个服务方法fileUpload()将根据 URL => FileUpload/fileUploadPage上的POST方法进行调用。将根据提交的信息准备要上传的文件。最后从服务方法返回“success”视图,这将呈现success.jsp视图。
fileUpload.jsp 的代码如下所示 -
<%@ page contentType="text/html; charset=UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>Spring MVC上传文件示例</title>
</head>
<body>
    <form:form method="POST" modelAttribute="fileUpload"
        enctype="multipart/form-data">
      请选择一个文件上传 :
      <input type="file" name="file" />
        <input type="submit" value="提交上传" />
    </form:form>
</body>
</html>
这里使用带有value =“fileUpload”的modelAttribute属性来映射文件用服务器模型上传控件。
success.jsp 的代码如下所示 -
<%@ page contentType="text/html; charset=UTF-8"%>
<html>
<head>
<title>Spring MVC上传文件示例</title>
</head>
<body>
    文件名称 :
    <b> ${fileName} </b> - 上传成功!
</body>
</html>
完成创建源和配置文件后,发布应用程序到Tomcat服务器。
现在启动Tomcat服务器,现在尝试访问URL => http://localhost:8080/FileUpload/fileUploadPage ,如果Spring Web应用程序没有问题,应该看到以下结果:

提交所需信息后,点击提交按钮提交表单。 如果 Spring Web 应用程序没有问题,应该看到以下结果:

Spring MVC文件上传处理的更多相关文章
- Spring MVC 笔记 —— Spring MVC 文件上传
		文件上传 配置MultipartResolver <bean id="multipartResolver" class="org.springframework.w ... 
- Spring MVC文件上传教程 commons-io/commons-uploadfile
		Spring MVC文件上传教程 commons-io/commons-uploadfile 用到的依赖jar包: commons-fileupload 1.3.1 commons-io 2.4 基于 ... 
- 【Java Web开发学习】Spring MVC文件上传
		[Java Web开发学习]Spring MVC文件上传 转载:https://www.cnblogs.com/yangchongxing/p/9290489.html 文件上传有两种实现方式,都比较 ... 
- Spring mvc文件上传实现
		Spring mvc文件上传实现 jsp页面客户端表单编写 三个要素: 1.表单项type="file" 2.表单的提交方式:post 3.表单的enctype属性是多部分表单形式 ... 
- Spring mvc 文件上传到文件夹(转载+心得)
		spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方1.form的enctype=”multipart/form-data” 这个是上传文件必须的2.applicationConte ... 
- spring mvc 文件上传 ajax 异步上传
		异常代码: 1.the request doesn't contain a multipart/form-data or multipart/mixed stream, content type he ... 
- spring mvc文件上传(单个文件上传|多个文件上传)
		单个文件上传spring mvc 实现文件上传需要引入两个必须的jar包 1.所需jar包: commons-fileupload-1.3.1.jar ... 
- Strut2 和Spring MVC 文件上传对比
		在Java领域中,有两个常用的文件上传项目:一个是Apache组织Jakarta的Common-FileUpload组件 (http://commons.apache.org/proper/commo ... 
- Spring MVC 文件上传 & 文件下载
		索引: 开源Spring解决方案--lm.solution 参看代码 GitHub: pom.xml WebConfig.java index.jsp upload.jsp FileUploadCon ... 
- 【Spring】Spring MVC文件上传--整合bootstrap-fileinput和jQuery-File-Upload
		前言 这里分享两个使用Spring MVC进行文件上传的简单示例, 分别整合bootstrap-fileinput 和 Jquery File Upload , 代码十分简单, 都是入门的示例,因此这 ... 
随机推荐
- Matlab中向量场的绘制
			% quiver(x,y,u,v) % x,y是包含坐标位置的矩阵,而u和v则是包含偏导数的矩阵. % 例如绘制f(x,y)=y-3x-2x^2-3xy-3y^2的方法: % 先用gradient函数 ... 
- 【jQuery】jquery中 使用$('#parentUid').attr(parentUid);报错jquery-1.11.3.min.js:5 Uncaught TypeError: Cannot read property 'nodeType' of undefined
			jquery中 使用$('#parentUid').attr(parentUid);报错jquery-1.11.3.min.js:5 Uncaught TypeError: Cannot read p ... 
- C# 7 新特性-2
			在之前的C# 7 新特性博客中,我们谈到了Tuples,Record Type和Pattern Matching.这些都是C#新特性中最可能出现的.在本博客中,我们会提到更多的一些特性,虽然这些特性不 ... 
- 【JUnit4.10源码分析】6.1 排序和过滤
			abstract class ParentRunner<T> extends Runner implements Filterable,Sortable 本节介绍排序和过滤. (尽管JUn ... 
- javascript快速入门14--DOM基础
			DOM(Document Object Model)——文档对象模型 什么是DOM? Document Object Model (DOM)是HTML和XML文档的编程接口.它提供了上述文档的一种结构 ... 
- 【Docker】MySQL容器因为内存限制启动失败?
			参考资料: https://github.com/docker-library/mysql/issues/3 Improving MySQL's default configuration:http: ... 
- HTML5 Canvas 绘制库存变化折线 增加超储告罄线
			<!DOCTYPE html> <html lang="utf-8"> <meta http-equiv="Content-Type&quo ... 
- Mycat探索之旅(3)----Mycat的全局序列号
			一.本地文件方式 原理:此方式MyCAT将sequence配置到文件中,当使用到sequence中的配置后,MyCAT会更下classpath中的sequence_conf.properties文件中 ... 
- Memory Barriers
			这回该进入主题了. 上一文最后提到了 Memory Barriers ,即内存屏障.由于对一个 CPU 而言,a = 1; b = 1. 由于在中间加了内存屏障,在 X86 架构下,就 ... 
- Python——标准库  Sys模块
			---------------------------------------------------------------------------------------------------- ... 
