Spring MVC文件上传示例教程 - 单个和多个文件

文件上传是任何Web应用程序中非常常见的任务。我们之前已经看过如何在Servlet和Struts2文件上传中上传文件。今天我们将学习Spring文件上传,特别是单个和多个文件的Spring MVC文件上传

目录[ 隐藏 ]

  • 1 Spring MVC文件上传

    • 1.1 Apache Commons FileUpload的Maven依赖项
    • 1.2 Spring文件上传表单视图
    • 1.3 Spring MVC Multipart配置
    • 1.4 Spring文件上传控制器类
  • 2 Spring MVC文件上传示例

Spring MVC文件上传

Spring MVC框架通过集成Apache Commons FileUpload API为上传文件提供支持。上传文件的过程非常简单,需要简单的配置。我们将在STS中创建一个简单的Spring MVC项目,如下图所示。

大部分是由STS工具生成的样板代码,我们将重点关注利用Spring文件上传集成所需的更改。

Apache Commons FileUpload的Maven依赖项

首先,我们需要在我们的pom.xml文件中添加Apache Commons FileUpload依赖项,以便所需的jar文件是Web应用程序的一部分。下面是我的pom.xml文件中的依赖片段。


<!-- Apache Commons FileUpload -->
<dependency><groupId>commons-fileupload</groupId><artifactId>commons-fileupload</artifactId><version>1.3.1</version>
</dependency><!-- Apache Commons IO -->
<dependency><groupId>commons-io</groupId><artifactId>commons-io</artifactId><version>2.4</version>
</dependency>

Spring文件上传表单视图

我们将创建两个JSP页面,以允许在spring Web应用程序中上传单个和多个文件。

upload.jsp查看代码:


<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>Upload File Request Page</title>
</head>
<body><form method="POST" action="uploadFile" enctype="multipart/form-data">File to upload: <input type="file" name="file"><br /> Name: <input type="text" name="name"><br /> <br /> <input type="submit" value="Upload"> Press here to upload the file!</form>
</body>
</html>

uploadMultiple.jsp视图代码:


<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ page session="false" %>
<html>
<head>
<title>Upload Multiple File Request Page</title>
</head>
<body><form method="POST" action="uploadMultipleFile" enctype="multipart/form-data">File1 to upload: <input type="file" name="file"><br /> Name1: <input type="text" name="name"><br /> <br /> File2 to upload: <input type="file" name="file"><br /> Name2: <input type="text" name="name"><br /> <br /><input type="submit" value="Upload"> Press here to upload the file!</form>
</body>
</html>

请注意,这些文件是简单的HTML文件,我没有使用任何JSP或Spring标签来避免复杂性。需要注意的重要一点是,表单enctype应该是multipart / form-data,以便Spring Web应用程序知道请求包含需要处理的文件数据。

另请注意,对于多个文件,输入字段中的表单字段“file”和“name”是相同的,因此数据将以数组的形式发送。我们将获取输入数组并解析文件数据并将其存储在给定的文件名中。

Spring MVC Multipart配置

要利用Apache Commons FileUpload来处理多部分请求,我们需要做的就是multipartResolver使用class as 配置bean org.springframework.web.multipart.commons.CommonsMultipartResolver

我们的最终Spring配置文件如下所示。

servlet-context.xml代码:


<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"xmlns:context="http://www.springframework.org/schema/context"xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsdhttp://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"><!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure --><!-- Enables the Spring MVC @Controller programming model --><annotation-driven /><!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory --><resources mapping="/**" location="/" /><!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory --><beans:beanclass="org.springframework.web.servlet.view.InternalResourceViewResolver"><beans:property name="prefix" value="/WEB-INF/views/" /><beans:property name="suffix" value=".jsp" /></beans:bean><beans:bean id="multipartResolver"class="org.springframework.web.multipart.commons.CommonsMultipartResolver"><!-- setting maximum upload size --><beans:property name="maxUploadSize" value="100000" /></beans:bean><context:component-scan base-package="com.journaldev.spring.controller" /></beans:beans>

请注意,我通过为multipartResolver bean 提供maxUploadSize属性值来设置最大上载大小限制。如果您将查看类的源代码,您将看到名为multipartResolver的MultipartResolver变量已定义并在下面的方法中初始化。DispatcherServlet


private void initMultipartResolver(ApplicationContext context){try{this.multipartResolver = ((MultipartResolver)context.getBean("multipartResolver", MultipartResolver.class));if (this.logger.isDebugEnabled()) {this.logger.debug("Using MultipartResolver [" + this.multipartResolver + "]");}}catch (NoSuchBeanDefinitionException ex){this.multipartResolver = null;if (this.logger.isDebugEnabled())this.logger.debug("Unable to locate MultipartResolver with name 'multipartResolver': no multipart request handling provided");}}

使用此配置,任何具有enctype作为multipart / form-data的请求将在传递给Controller类之前由multipartResolver处理。

Spring文件上传控制器类

控制器类代码非常简单,我们需要为uploadFileuploadMultipleFile URI 定义处理程序方法。

FileUploadController.java代码:


package com.journaldev.spring.controller;import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;/*** Handles requests for the application file upload requests*/
@Controller
public class FileUploadController {private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class);/*** Upload single file using Spring Controller*/@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)public @ResponseBodyString uploadFileHandler(@RequestParam("name") String name,@RequestParam("file") MultipartFile file) {if (!file.isEmpty()) {try {byte[] bytes = file.getBytes();// Creating the directory to store fileString rootPath = System.getProperty("catalina.home");File dir = new File(rootPath + File.separator + "tmpFiles");if (!dir.exists())dir.mkdirs();// Create the file on serverFile serverFile = new File(dir.getAbsolutePath()+ File.separator + name);BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));stream.write(bytes);stream.close();logger.info("Server File Location="+ serverFile.getAbsolutePath());return "You successfully uploaded file=" + name;} catch (Exception e) {return "You failed to upload " + name + " => " + e.getMessage();}} else {return "You failed to upload " + name+ " because the file was empty.";}}/*** Upload multiple file using Spring Controller*/@RequestMapping(value = "/uploadMultipleFile", method = RequestMethod.POST)public @ResponseBodyString uploadMultipleFileHandler(@RequestParam("name") String[] names,@RequestParam("file") MultipartFile[] files) {if (files.length != names.length)return "Mandatory information missing";String message = "";for (int i = 0; i < files.length; i++) {MultipartFile file = files[i];String name = names[i];try {byte[] bytes = file.getBytes();// Creating the directory to store fileString rootPath = System.getProperty("catalina.home");File dir = new File(rootPath + File.separator + "tmpFiles");if (!dir.exists())dir.mkdirs();// Create the file on serverFile serverFile = new File(dir.getAbsolutePath()+ File.separator + name);BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(serverFile));stream.write(bytes);stream.close();logger.info("Server File Location="+ serverFile.getAbsolutePath());message = message + "You successfully uploaded file=" + name+ "<br />";} catch (Exception e) {return "You failed to upload " + name + " => " + e.getMessage();}}return message;}
}

请注意Spring注释的使用,这些注释使我们的生活更轻松,代码看起来更具可读性。

uploadFileHandler方法用于处理单个文件上载方案,而uploadMultipleFileHandler方法用于处理多个文件上载方案。实际上,我们可以使用一种方法来处理这两种情况。

现在将应用程序导出为WAR文件并将其部署到Tomcat servlet容器中。

当我们运行我们的应用程序时,下面的图像向我们显示请求和响应。

Spring MVC文件上传示例

您可以检查服务器日志以了解文件的存储位置。

从上面的链接下载项目并使用它来了解更多信息。

下载Spring文件上传项目

转载来源:https://www.journaldev.com/2573/spring-mvc-file-upload-example-single-multiple-files

Spring MVC文件上传示例教程 - 单个和多个文件相关推荐

  1. Spring Boot文件上传示例

    一.创建一个简单的包含WEB依赖的SpringBoot项目 pom.xml内容: <!-- Spring Boot web启动器 --> <dependency><gro ...

  2. Spring MVC实现上传文件报错解决方案

    Spring MVC实现上传文件报错解决方案 参考文章: (1)Spring MVC实现上传文件报错解决方案 (2)https://www.cnblogs.com/liuling/p/2014-3-5 ...

  3. spring mvc(注解)上传文件的简单例子

    spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方 1.form的enctype="multipart/form-data" 这个是上传文件必须的 2.appl ...

  4. Spring MVC 如何上传多个文件到指定位置

    Spring MVC 如何上传多个文件到指定位置 太阳火神的美丽人生 (http://blog.csdn.net/opengl_es) 本文遵循"署名-非商业用途-保持一致"创作公 ...

  5. jsp servlet示例_Servlet和JSP中的文件上传示例

    jsp servlet示例 使用Servlet和JSP将文件上传到服务器是Java Web应用程序中的常见任务. 在对Servlet或JSP进行编码以处理文件上传请求之前,您需要了解一点有关HTML和 ...

  6. Servlet和JSP中的文件上传示例

    使用Servlet和JSP将文件上传到服务器是Java Web应用程序中的常见任务. 在对Servlet或JSP进行编码以处理文件上传请求之前,您需要了解一点有关HTML和HTTP协议中文件上传支持的 ...

  7. struts2登录注册示例_Struts 2文件上传示例

    struts2登录注册示例 Welcome to Struts 2 file upload example. File Upload is one of the common tasks of a w ...

  8. Spring Boot文件上传及回显(单/多文件)

    一.单文件上传 1.前端页面 <!DOCTYPE html> <html lang="en"> <head><meta charset=& ...

  9. angular上传文件到本地服务器,Angular文件上传示例

    以下为Angular的文件上传示例,分为三个步骤. 步骤一.创建HTML模板 (file-upload.component.html) 简单的创建一个类型为file的input标签,input上添加c ...

最新文章

  1. 牛红红的日记(平平无奇拿下域控)
  2. function “printf“ declared implicitly
  3. IBM Watson IoT
  4. 前端框架 Angular 11.0.0 正式发布,已经放弃 IE 9 、10
  5. 【python 图像识别】python 身份证号码识别
  6. 前端开发工程师面试题
  7. 使用IBM ServerGuide安装操作系统
  8. opencv图片保存0字节_Opencv中IplImage存储方式介绍
  9. 【PS功能学习】10:蒙版带你领略台前幕后的故事
  10. luogu P5867 【[SEERC2018]Fishermen】
  11. Vue-生命周期(函数)
  12. RHEL 7 常用命令
  13. html5网页制作心得体会,网页设计课程学习心得总结
  14. 测试开发面试(八)——进程与线程、python数据结构、数据库
  15. Java中随机数的产生方法
  16. 计算机英语的save,save是什么意思_save在线翻译_英语_读音_用法_例句_海词词典
  17. mysql如何用_如何使用mysql
  18. 用什么软件工具可以一键添加渐入效果同时虚化边框背景呢?
  19. 程序员绝不要做“IT民工”
  20. 【美少女】字节跳动直通车?不坐白不坐

热门文章

  1. JS 获取链接(url)参数以及锚链接(anchor)结合富ajax的应用(ajax前进/后退的问题)...
  2. 剑指offer 31.栈的、压入弹出序列
  3. C++读写表格csv——文本与表格完美桥接者
  4. J-LINK 操作使用指南
  5. 本地Vue前端请求本地Spring Boot跨域问题(CROS错误)
  6. 【今日CS 视觉论文速览】Fri, 18 Jan 2019
  7. Maven——windows下安装配置及IDEA设置本地仓库的步骤总结
  8. python-第一个python程序-向世界问好
  9. 2018年黑龙江由俄进口原油2725.2万吨同比增加67.1%
  10. 开发者都应该知道的15个API