更新時(shí)間:2022-12-05 11:18:54 來(lái)源:動(dòng)力節(jié)點(diǎn) 瀏覽1107次
文件上傳是任何 Web 應(yīng)用程序中非常常見(jiàn)的任務(wù)。下面我們將學(xué)習(xí)Spring 文件上傳,特別是針對(duì)單個(gè)文件和多個(gè)文件的Spring MVC 文件上傳。
Spring MVC 框架通過(guò)集成 Apache Commons FileUpload API 提供了對(duì)文件上傳的支持。上傳文件的過(guò)程非常簡(jiǎn)單,只需要簡(jiǎn)單的配置。我們將在 STS 中創(chuàng)建一個(gè)簡(jiǎn)單的Spring MVC項(xiàng)目,如下圖所示。
大部分部分是由 STS 工具生成的樣板代碼,我們將重點(diǎn)關(guān)注使用 Spring 文件上傳集成所需的更改。
首先,我們需要在我們的 pom.xml 文件中添加 Apache Commons FileUpload 依賴(lài)項(xiàng),以便所需的 jar 文件成為 Web 應(yīng)用程序的一部分。下面是我的 pom.xml 文件中的依賴(lài)片段。
<!-- 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>
我們將創(chuàng)建兩個(gè) JSP 頁(yè)面以允許在 spring web 應(yīng)用程序中上傳單個(gè)和多個(gè)文件。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>
請(qǐng)注意,這些文件是簡(jiǎn)單的 HTML 文件,我沒(méi)有使用任何 JSP 或 Spring 標(biāo)記以避免復(fù)雜性。需要注意的重點(diǎn)是 form enctype應(yīng)該是multipart/form-data,這樣 Spring web 應(yīng)用程序就知道請(qǐng)求包含需要處理的文件數(shù)據(jù)。還要注意,對(duì)于多個(gè)文件,輸入字段中的表單字段“文件”和“名稱(chēng)”是相同的,因此數(shù)據(jù)將以數(shù)組的形式發(fā)送。我們將獲取輸入數(shù)組并解析文件數(shù)據(jù)并將其存儲(chǔ)在給定的文件名中。
要利用 Apache Commons FileUpload 處理多部分請(qǐng)求,我們需要做的就是將multipartResolverbean 配置為 class 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>
請(qǐng)注意,我通過(guò)為multipartResolver bean提供maxUploadSize屬性值來(lái)設(shè)置最大上傳大小限制。如果您查看類(lèi)的源代碼,您會(huì)看到在下面的方法中定義并初始化了一個(gè)名為 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 的請(qǐng)求都將在傳遞給 Controller 類(lèi)之前由 multipartResolver 處理。
控制器類(lèi)代碼非常簡(jiǎn)單,我們需要為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();
// 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;
}
}
請(qǐng)注意使用 Spring 注釋使我們的生活更輕松,代碼看起來(lái)更易讀。uploadFileHandlermethod 用于處理單個(gè)文件上傳場(chǎng)景,而uploadMultipleFileHandlermethod 用于處理多個(gè)文件上傳場(chǎng)景。實(shí)際上,我們可以用一種方法來(lái)處理這兩種情況。現(xiàn)在將應(yīng)用程序?qū)С鰹?WAR 文件并將其部署到 Tomcat servlet 容器中。當(dāng)我們運(yùn)行我們的應(yīng)用程序時(shí),下圖向我們展示了請(qǐng)求和響應(yīng)。
您可以檢查服務(wù)器日志以了解文件的存儲(chǔ)位置。如果大家想了解更多相關(guān)知識(shí),不妨來(lái)關(guān)注一下本站的SpringMVC教程,里面還有更豐富的知識(shí)等著大家去學(xué)習(xí),希望對(duì)大家能夠有所幫助。
0基礎(chǔ) 0學(xué)費(fèi) 15天面授
有基礎(chǔ) 直達(dá)就業(yè)
業(yè)余時(shí)間 高薪轉(zhuǎn)行
工作1~3年,加薪神器
工作3~5年,晉升架構(gòu)
提交申請(qǐng)后,顧問(wèn)老師會(huì)電話(huà)與您溝通安排學(xué)習(xí)
初級(jí) 202925
初級(jí) 203221
初級(jí) 202629
初級(jí) 203743