- Spring Boot war包启动
- 什么是Spring boot
- 快速了解Spring Boot
- Spring boot入门实例
- springboot 整合freemarker
- Spring Boot使用FastJson解析JSON数据
- Spring Boot上传文件示例
开源项目
知识点
相关文章
更多最近更新
更多Spring Boot上传文件示例
2019-04-29 23:30|来源: 网路
本文介绍如何在Spring Boot Web应用程序中上传文件。
使用的工具 :
Spring Boot 1.4.3.RELEASE
Spring 4.3.5.RELEASE
Thymeleaf
Maven 3
Embedded Tomcat 8.5.6
1. 项目依赖
Spring boot依赖关系,无需额外的文件上传库。
<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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com656463</groupId> <artifactId>spring-boot-file-upload</artifactId> <packaging>jar</packaging> <version>1.0</version> <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> <!-- hot swapping, disable cache for template, enable live reload --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> </dependencies> <build> <plugins> <!-- Package as an executable jar/war --> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project>
2.文件上传示例
Spring Boot文件上传,不需要什么特别的配置。在Controller中,将上传的文件映射到MultipartFile
。
文件:UploadController.java -
package com656463.controller; 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; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @Controller public class UploadController { //Save the uploaded file to this folder private static String UPLOADED_FOLDER = "D://temp//"; @GetMapping("/") public String index() { return "upload"; } @PostMapping("/upload") // //new annotation since 4.3 public String singleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) { if (file.isEmpty()) { redirectAttributes.addFlashAttribute("message", "Please select a file to upload"); return "redirect:uploadStatus"; } try { // Get the file and save it somewhere byte[] bytes = file.getBytes(); Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename()); Files.write(path, bytes); redirectAttributes.addFlashAttribute("message", "You successfully uploaded '" + file.getOriginalFilename() + "'"); } catch (IOException e) { e.printStackTrace(); } return "redirect:/uploadStatus"; } @GetMapping("/uploadStatus") public String uploadStatus() { return "uploadStatus"; } }
在thymeleaf
,只是一些普通的HTML文件标签。文件:upload.html
-
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <body> <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>
另外一个页面,用为显示文件上传的状态。文件:uploadStatus.html
-
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <body> <h1>Spring Boot文件上传状态</h1> <div th:if="${message}"> <h2 th:text="${message}"/> </div> </body> </html>
3. 超过最大上传大小
要处理最大上传大小超出异常,请声明一个@ControllerAdvice
并捕获MultipartException
。
文件:GlobalExceptionHandler.java
package com656463.controller; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.multipart.MultipartException; import org.springframework.web.servlet.mvc.support.RedirectAttributes; @ControllerAdvice public class GlobalExceptionHandler { //http://jira.spring.io/browse/SPR-14651 //4.3.5 supports RedirectAttributes redirectAttributes @ExceptionHandler(MultipartException.class) public String handleError1(MultipartException e, RedirectAttributes redirectAttributes) { redirectAttributes.addFlashAttribute("message", e.getCause().getMessage()); return "redirect:/uploadStatus"; } }
4. Tomcat连接重置
如果部署到Tomcat,请配置maxSwallowSize
以避免此Tomcat连接重置问题。 对于嵌入式Tomcat,声明一个TomcatEmbeddedServletContainerFactory
,如下所示, SpringBootWebApplication.java -
package com656463; 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; //http://www.agilegroup.co.jp/technote/springboot-fileupload-error-handling.html @SpringBootApplication public class SpringBootWebApplication { private int maxUploadSizeInMb = 10 * 1024 * 1024; // 10 MB 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; } }
5. Multipart文件大小
默认情况下,Spring Boot max文件上传大小为1MB
,可以通过以下应用程序属性来配置它的值,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
6. 运行示例
使用默认的嵌入式Tomcat启动Spring Boot的命令如下: mvn spring-boot:run
,运行结果如下 -
23:40:03,238 |-INFO in ch.qos.logback.classic.joran.JoranConfigurator@5a39699c - Registering current configuration as safe fallback point . ____ _ __ _ _ /\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \ ( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \ \\/ ___)| |_)| | | | | || (_| | ) ) ) ) ' |____| .__|_| |_|_| |_\__, | / / / / =========|_|==============|___/=/_/_/_/ ::Spring Boot:: (v1.4.3.RELEASE) 2017-03-30 23:40:04 INFO cn.sxt.SpringBootWebApplication - Starting SpringBootWebApplication on MY-PC with PID 880 (F:\worksp\springboot\file-upload\target\classes started by Administrator in F:\worksp\springboot\file-upload) 2017-03-30 23:40:04 DEBUG cn.sxt.SpringBootWebApplication - Running with Spring Boot v1.4.3.RELEASE, Spring v4.3.5.RELEASE 2017-03-30 23:40:04 INFO cn.sxt.SpringBootWebApplication - No active profile set, falling back to default profiles: default 2017-03-30 23:40:08 INFO cn.sxt.SpringBootWebApplication - Started SpringBootWebApplication in 5.359 seconds (JVM running for 6.355)
选择一个文件并将其上传,选择大于10mb
的文件,将会看到页面提示如下 -
相关问答
更多-
是不是有一款什么手机软件,可以很自然的拉长腿部?不是美图秀秀,有知道的不?[2022-10-20]
spring -
Spring Boot怎么处理上传文件时出现的MultipartException[2021-10-04]
Spring Boot处理上传文件时出现的MultipartException的解决办法 1、文件上传大小可在js框架里就做验证了。推荐JS上传框架uploadify.js 2、既然使用了springboot,那你的文件上传的处理应该在Controller里处理。 3、如果你需要的仅仅是错误信息跳转到错误页面而不是打印堆栈信息,只需要实现一个@RequestMapping(value = "/error")的Controller实现。 -
Spring Boot怎么处理上传文件时出现的MultipartException[2022-02-18]
1、文件上传大小可在js框架里就做验证了。推荐JS上传框架uploadify.js 2、既然使用了springboot,那你的文件上传的处理应该在Controller里处理。 3、如果你需要的仅仅是错误信息跳转到错误页面而不是打印堆栈信息,只需要实现一个@RequestMapping(value = "/error")的Controller实现。 -
春天的英语怎么读?[2022-05-21]
spring -
Spring启动使用maven作为构建工具,因此您可以将项目作为现有maven项目导入。 然后m2e eclipse插件将从mavens pom.xml文件生成eclipse设置。 从文件系统导入尝试导入现有的eclipse项目,但是春季启动演示不包括eclipse设置,因为它们独立于IDE Spring boot uses maven as build tool, so you can import the project as existing maven project. The m2e eclips ...
-
SO上有其他一些解决方案: 发布spring boot可执行jar工件 : artifact(file("$buildDir/$project.name-$project.version-${bootRepackage.classifier}.jar")) { classifier 'exec' } Gradle maven-publish不构建独立的spring-boot应用程序 : publish { dependsOn assemble } There is a couple s ...
-
解决方案是更新Spring Boot(多部分autoconfig中的一个错误已得到修复,可能就是这样)。 Resolution was to update Spring Boot (a bug in the multipart autoconfig had been fixed so that was probably it).
-
用spring spring mvc 4和spring boot上传html5多文件(html5 multiple file upload with spring mvc 4 and spring boot)[2021-03-08]
为了防止有人面临同样的问题,事实证明它与春天和百里香无关。 这只是因为我使用的主题使用bootstrap fileinput插件,它以两种模式工作:ajax和表单提交。 事实证明,主题在文件上传中使用的大多数功能在表单提交模式下都不可用。 所以这是第三方lib问题,但我想我应该分享。 Just in case somebody faces the same issue, it turned out that it has nothing to do with spring nor thymeleaf. It ... -
spring boot文件上传错误(spring boot file upload error)[2023-08-19]
该错误表明你的FileUploadController存在问题,bean是冲突的,两个同名的类,Spring无法确定使用哪一个,尝试创建别名和限定符或给它一个不同的名称,所以它不冲突。 有关使用spring boot和文件上传的示例,请查看以下示例: https : //github.com/Rob-Leggett/gradle_springboot_microservice The error indicates you have an issue with your FileUploadControll ... -
你有 @RequestMapping("/api") public class FileUploadController { 这意味着您的请求将以/api开头 要达到listUploadedFiles方法,你需要点击localhost:8080 / api / You have @RequestMapping("/api") public class FileUploadController { which means your requests will start with /api to reac ...