Учебное пособие по примерам загрузки файлов Spring MVC — одиночные и несколько файлов
Загрузка файлов — очень распространенная задача в любом веб-приложении. Ранее мы видели, как загружать файлы Struts2. Сегодня мы узнаем о загрузке файлов Spring, в частности, о загрузке файлов Spring MVC для одного и нескольких файлов.
Загрузка файла Spring MVC
Зависимости Maven для Apache Commons FileUpload
Прежде всего, нам нужно добавить зависимости Apache Commons FileUpload в наш файл pom.xml, чтобы необходимые файлы jar были частью веб-приложения. Ниже приведен фрагмент зависимости из моего файла 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, чтобы разрешить загрузку одного и нескольких файлов в весеннее веб-приложение. upload.jsp код просмотра:
<%@ taglib uri="https://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="https://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 знало, что запрос содержит данные файла, которые необходимо обработать. Также обратите внимание, что для нескольких файлов поля формы «файл» и «имя» совпадают в полях ввода, поэтому данные будут отправлены в виде массива. Мы возьмем входной массив, проанализируем данные файла и сохраним их в заданном имени файла.
Spring Многокомпонентная конфигурация MVC
Чтобы использовать Apache Commons FileUpload для обработки составных запросов, все, что нам нужно сделать, это настроить bean-компонент multipartResolver
с классом org.springframework.web.multipart.commons.CommonsMultipartResolver
. Наш окончательный файл конфигурации Spring выглядит следующим образом. код servlet-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="https://www.springframework.org/schema/mvc"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns:beans="https://www.springframework.org/schema/beans"
xmlns:context="https://www.springframework.org/schema/context"
xsi:schemaLocation="https://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd
https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd
https://www.springframework.org/schema/context https://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:bean
class="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>
Обратите внимание, что я устанавливаю ограничение максимального размера загрузки, предоставляя значение свойства maxUploadSize для bean-компонента multipartResolver. Если вы посмотрите на исходный код класса DispatcherServlet
, вы увидите, что переменная MultipartResolver с именем multipartResolver определена и инициализирована в методе ниже.
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 будет обрабатываться multipartResolver перед передачей классу Controller.
Класс контроллера загрузки файлов Spring
Код класса контроллера очень прост, нам нужно определить методы-обработчики для URI uploadFile и uploadMultipleFile. Код 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 @ResponseBody
String uploadFileHandler(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// Creating the directory to store file
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "tmpFiles");
if (!dir.exists())
dir.mkdirs();
// Create the file on server
File 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 @ResponseBody
String 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 file
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "tmpFiles");
if (!dir.exists())
dir.mkdirs();
// Create the file on server
File 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. Когда мы запускаем наше приложение, на изображениях ниже показаны запрос и ответы.
Пример загрузки файла Spring MVC
Скачать проект загрузки файлов Spring