大战熟女丰满人妻av-荡女精品导航-岛国aaaa级午夜福利片-岛国av动作片在线观看-岛国av无码免费无禁网站-岛国大片激情做爰视频

專(zhuān)注Java教育14年 全國(guó)咨詢(xún)/投訴熱線(xiàn):400-8080-105
動(dòng)力節(jié)點(diǎn)LOGO圖
始于2009,口口相傳的Java黃埔軍校
首頁(yè) hot資訊 SpringMVC上傳下載實(shí)例

SpringMVC上傳下載實(shí)例

更新時(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 文件上傳

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 文件上傳集成所需的更改。

Apache Commons FileUpload 的 Maven 依賴(lài)項(xiàng)

首先,我們需要在我們的 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>

Spring 文件上傳表單視圖

我們將創(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ǔ)在給定的文件名中。

Spring MVC 多部分配置

要利用 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 處理。

Spring文件上傳控制器類(lèi)

控制器類(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)。

Spring MVC 文件上傳示例

您可以檢查服務(wù)器日志以了解文件的存儲(chǔ)位置。如果大家想了解更多相關(guān)知識(shí),不妨來(lái)關(guān)注一下本站的SpringMVC教程,里面還有更豐富的知識(shí)等著大家去學(xué)習(xí),希望對(duì)大家能夠有所幫助。

提交申請(qǐng)后,顧問(wèn)老師會(huì)電話(huà)與您溝通安排學(xué)習(xí)

  • 全國(guó)校區(qū) 2025-04-24 搶座中
  • 全國(guó)校區(qū) 2025-05-15 搶座中
  • 全國(guó)校區(qū) 2025-06-05 搶座中
  • 全國(guó)校區(qū) 2025-06-26 搶座中
免費(fèi)課程推薦 >>
技術(shù)文檔推薦 >>
主站蜘蛛池模板: 久久精品免费一区二区三区 | 久久青青草原精品国产麻豆 | 大陆一级毛片免费视频观看 | 99在线视频精品费观看视 | 久久亚洲欧美成人精品 | 欧美日韩国产亚洲一区二区三区 | 国产成人精品久久综合 | 一级特黄aaa大片在线观看 | 国产成视频 | 97啪啪 | 国产麻豆之光e奶女教师 | 日本黄页网 | 99视频全部免费 | 欧美精品一区二区三区在线播放 | 久久婷婷激情 | www.欧美成人 | 在线看福利视频120秒 | 99日影院在线播放 | 欧美日本视频一区 | 成人黄色在线免费观看 | 2021久久精品国产99国产 | 国产在线一91区免费国产91 | 亚洲精品久久99久久一 | 老司机福利深夜亚洲入口 | 亚洲欧美日韩国产精品久久 | 久操网址| 性色黄| 国产精品日韩欧美久久综合 | 私人影院aaaaa毛片 | 一区二区三区视频观看 | 成人午夜看片在线观看 | 亚洲视频免 | 麻豆精品国产免费观看 | 日韩欧美在线视频 | 亚色在线视频 | 一级片久久| 九九激情视频 | 国产精品久久久久免费a∨ 国产精品久久久久免费视频 | 综合网婷婷 | 五月综合色 | 在线看的成人性视频 |