Spring Boot 上传文件(spring boot upload file)

xiaoxiao2021-02-28  86

本篇文章将说明在Spring Boot web程序中如何上传文件。

开发环境:

1. eclipse Oxygen Release (4.7.0)

2. Spring Boot 1.4.3 RELEASE

3. Spring 4.3.5 RELEASE

4. Thymelaef

5. Maven

6. Embedded Tomcat 8

1.最终的项目结构

2.项目所需依赖 pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>org.thinkingingis</groupId> <artifactId>spring-boot-fileupload</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>spring-boot-fileupload</name> <url>http://maven.apache.org</url> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.4.3.RELEASE</version> </parent> <properties> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> 3. UploadController.java

用MultipartFile类去匹配上传的文件

package org.thinkingingis.controller; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.mvc.support.RedirectAttributes; @Controller public class UploadController { private static String UPLOAD_FOLDER = "H://temp//"; @GetMapping("/") public String index() { return "upload"; } @PostMapping("/upload") public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) { if(file.isEmpty()) { redirectAttributes.addFlashAttribute("message", "请选择一个上传文件"); } try { byte[] bytes = file.getBytes(); Path path = Paths.get(UPLOAD_FOLDER + file.getOriginalFilename()); Files.write(path, bytes); redirectAttributes.addFlashAttribute("message", "已经将 '" + file.getOriginalFilename() + "' 的文件上传成功"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return "redirect:/uploadStatus"; } @GetMapping("/uploadStatus") public String uploadStatus() { return "uploadStatus"; } } 4. Thymeleaf 前端页面

4.1 upload.html

<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <h1>ThinkingInGIS</h1> <br/> <h1>Spring Boot 文件上传示例</h1> <form method="POST" action="/upload" enctype="multipart/form-data"> <input type="file" name="file" /><br/><br/> <input type="submit" value="上传" /> </form> </body> </html>4.2  uploadStatus.html

<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <h1>Spring Boot - 上传状态</h1> <div th:if="${message}"> <h2 th:text="${message}"></h2> </div> </body> </html>5. 处理文件过大的情况

下面 GlobalExceptionHandler.java 这个类是处理当上传文件超过10mb限制所引发的异常情况。

package org.thinkingingis.controller; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.multipart.MultipartException; import org.springframework.web.servlet.mvc.support.RedirectAttributes; @ControllerAdvice public class GlobalExceptionHandler { public String handerError(MultipartException e, RedirectAttributes redirectAttributes) { redirectAttributes.addFlashAttribute("message", e.getCause().getMessage()); return "redirect:/uploadStatus"; } } 6. Tomcat大文件重置连接

对于embedded tomcat ,需要声明TomcatEmbeddedServletContainerFactory

package org.thinkingingis.controller; import org.apache.coyote.http11.AbstractHttp11Protocol; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.embedded.tomcat.TomcatConnectorCustomizer; import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory; import org.springframework.context.annotation.Bean; @SpringBootApplication public class SpringBootWebApplication { //private int maxUploadFileSize = 10 * 1024 * 1024; public static void main(String[] args) throws Exception { SpringApplication.run(SpringBootWebApplication.class, args); } //Tomcat large file upload connection reset @Bean public TomcatEmbeddedServletContainerFactory tomcatEmbedded() { TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory(); tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> { if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) { //-1 means unlimited ((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1); } }); return tomcat; } }

7. 在application.properties中设置上传文件的上限

#http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#common-application-properties #search multipart spring.http.multipart.max-file-size=10MB spring.http.multipart.max-request-size=10MB

8. 进入项目文件  输入 mvn spring-boot:run

9. 启动成功后浏览器输入 localhost:8080

上传成功后

到此就实现了Spring Boot上传文件的功能。

如遇到问题,欢迎通过公众号留言给作者,以便共同探讨。

邮箱:thinkingingis@qq.com

微信公众号:

转载请注明原文地址: https://www.6miu.com/read-27335.html

最新回复(0)