檔案上傳是任何網路應用程式中非常常見的任務。我們之前已經看過如何在 Servlet 和 Struts2 中上傳檔案。今天我們將了解 Spring 的檔案上傳,具體來說是 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="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 Web 應用程序知道請求包含需要處理的文件數據。同樣注意,對於多個文件,表單字段 “file” 和 “name” 在輸入字段中相同,以便數據將以數組的形式發送。我們將取得輸入數組,解析文件數據並將其存儲在給定的文件名中。
Spring MVC 多部分配置
要使用 Apache Commons FileUpload 处理多部分请求,我们只需配置 multipartResolver
bean,并将类设置为 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>
注意,我通过为 multipartResolver bean 提供 maxUploadSize 属性值来设置最大上传大小限制。如果您查看 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 的请求都将在传递给 Controller 类之前由 multipartResolver 处理。
Spring 文件上传 Controller 类
Controller 类代码非常简单,我们需要为 uploadFile 和 uploadMultipleFile 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 @ResponseBody
String uploadFileHandler(@RequestParam("name") String name,
@RequestParam("file") MultipartFile file) {
if (!file.isEmpty()) {
try {
byte[] bytes = file.getBytes();
// 創建存儲文件的目錄
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "tmpFiles");
if (!dir.exists())
dir.mkdirs();
// 在服務器上創建文件
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();
// 創建存儲文件的目錄
String rootPath = System.getProperty("catalina.home");
File dir = new File(rootPath + File.separator + "tmpFiles");
if (!dir.exists())
dir.mkdirs();
// 在服務器上創建文件
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
+ "
";
} catch (Exception e) {
return "You failed to upload " + name + " => " + e.getMessage();
}
}
return message;
}
}
請注意使用了Spring註釋,使我們的生活更輕鬆,代碼看起來更可讀。 uploadFileHandler
方法用於處理單文件上傳場景,而 uploadMultipleFileHandler
方法用於處理多文件上傳場景。 實際上,我們可以使用一個單一方法來處理這兩種情況。 現在將應用程序導出為WAR文件並部署到Tomcat Servlet容器中。 當我們運行應用程序時,下面的圖像顯示了請求和響應。