在启动类中添加
/** * tomcatEmbedded 这段代码是为了解决,上传文件大于10M出现连接重置的问题。 * 此异常内容 GlobalException 也捕获不到。 * @return */ @Bean public TomcatServletWebServerFactory tomcatEmbedded() { TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory(); tomcat.addConnectorCustomizers((TomcatConnectorCustomizer) connector -> { if ((connector.getProtocolHandler() instanceof AbstractHttp11Protocol<?>)) { // -1 means unlimited ((AbstractHttp11Protocol<?>) connector.getProtocolHandler()).setMaxSwallowSize(-1); } }); return tomcat; }简单的上传页面编写
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1>上传实例</h1> <form method="POST" action="/upload" enctype="multipart/form-data"> <input type="file" name="file" /><br/><br/> <input type="submit" value="Submit" /> </form> </body> </body> </html>结果页面
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <h1>上传结果展示:</h1> <div th:if="${message}"> <h2 th:text="${message}" /> </div> </body> </html>MultipartFile是Spring上传文件的封装类,包含了文件的二进制流和文件属性等信息,在配置文件中也可对相关属性进行配置,基本的配置信息如下:
#默认支持文件上传. # spring.http.multipart.enabled=true #支持文件写入磁盘. # spring.http.multipart.file-size-threshold=0 # 上传文件的临时目录 # spring.http.multipart.location= # 最大支持文件大小 spring.http.multipart.max-file-size=1Mb # 最大支持请求大小 spring.http.multipart.max-request-size=10Mb
测试:
关于上传和SpringMVC区别不大,到此就完成springboot上传功能。
如果本文对您有很大的帮助,还请点赞关注一下。