本篇文章給大家分享的是有關(guān)SpringBoot中怎么利用Thymeleaf上傳文件,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
創(chuàng)新互聯(lián)專注于安陽(yáng)企業(yè)網(wǎng)站建設(shè),成都響應(yīng)式網(wǎng)站建設(shè)公司,商城網(wǎng)站制作。安陽(yáng)網(wǎng)站建設(shè)公司,為安陽(yáng)等地區(qū)提供建站服務(wù)。全流程定制網(wǎng)站建設(shè),專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
引入了 spring-boot-starter-thymeleaf 做頁(yè)面模板引擎。
常用配置內(nèi)容,單位支持 MB 或者 KB:
#支持的最大文件 spring.servlet.multipart.max-file-size=100MB #文件請(qǐng)求最大限制 spring.servlet.multipart.max-request-size=100MB
以上配置主要是通過設(shè)置 MultipartFile 的屬性來控制上傳限制,MultipartFile 是 Spring 上傳文件的封裝類,包含了文件的二進(jìn)制流和文件屬性等信息,在配置文件中也可對(duì)相關(guān)屬性進(jìn)行配置。
除過以上配置,常用的配置信息如下:
spring.servlet.multipart.enabled=true,是否支持 multipart 上傳文件
spring.servlet.multipart.file-size-threshold=0,支持文件寫入磁盤
spring.servlet.multipart.location=,上傳文件的臨時(shí)目錄
spring.servlet.multipart.max-file-size=10Mb,最大支持文件大小
spring.servlet.multipart.max-request-sizee=10Mb,最大支持請(qǐng)求大小
spring.servlet.multipart.resolve-lazily=false,是否支持 multipart 上傳文件時(shí)懶加載
@SpringBootApplication
public class FileUploadWebApplication {
public static void main(String[] args) throws Exception {
SpringApplication.run(FileUploadWebApplication.class, args);
}
//Tomcat large file upload connection reset
@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;
}
}TomcatServletWebServerFactory() 方法主要是為了解決上傳文件大于 10M 出現(xiàn)連接重置的問題,此異常內(nèi)容 GlobalException 也捕獲不到。
上傳頁(yè)面:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <body> <h2>Spring Boot file upload example</h2> <form method="POST" action="/upload" enctype="multipart/form-data"> <input type="file" name="file" /><br/><br/> <input type="submit" value="Submit" /> </form> </body> </html>
非常簡(jiǎn)單的一個(gè) Post 請(qǐng)求,一個(gè)選擇框選擇文件、一個(gè)提交按鈕,效果如下:
上傳結(jié)果展示頁(yè)面:
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<h2>Spring Boot - Upload Status</h2>
<div th:if="${message}">
<h3 th:text="${message}"/>
</div>
</body>
</html>效果圖如下:

訪問 localhost:8080 自動(dòng)跳轉(zhuǎn)到上傳頁(yè)面:
@GetMapping("/")
public String index() {
return "upload";
}上傳業(yè)務(wù)處理:
@PostMapping("/upload")
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();
// UPLOADED_FOLDER 文件本地存儲(chǔ)地址
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";
}上面代碼的意思就是,通過 MultipartFile 讀取文件信息,如果文件為空跳轉(zhuǎn)到結(jié)果頁(yè)并給出提示;如果不為空讀取文件流并寫入到指定目錄,最后將結(jié)果展示到頁(yè)面。最常用的是最后兩個(gè)配置內(nèi)容,限制文件上傳大小,上傳時(shí)超過大小會(huì)拋出異常:

當(dāng)然在真實(shí)的項(xiàng)目中我們可以在業(yè)務(wù)中會(huì)首先對(duì)文件大小進(jìn)行判斷,再將返回信息展示到頁(yè)面。
這里演示的是 MultipartException 的異常處理,也可以稍微改造監(jiān)控整個(gè)項(xiàng)目的異常問題。
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MultipartException.class)
public String handleError1(MultipartException e, RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("message", e.getCause().getMessage());
return "redirect:/uploadStatus";
}
}在項(xiàng)目中經(jīng)常會(huì)有一次性上傳多個(gè)文件的需求,我們稍作修改即可支持。
首先添加可以支持上傳多文件的頁(yè)面,內(nèi)容如下:
<!DOCTYPE html> <html xmlns:th="http://www.thymeleaf.org"> <body> <h2>Spring Boot files upload example</h2> <form method="POST" action="/uploadMore" enctype="multipart/form-data"> 文件1: <input type="file" name="file" /><br/><br/> 文件2: <input type="file" name="file" /><br/><br/> 文件3: <input type="file" name="file" /><br/><br/> <input type="submit" value="Submit" /> </form> </body> </html>
后端添加頁(yè)面訪問入口:
@GetMapping("/more")
public String uploadMore() {
return "uploadMore";
}在瀏覽器中輸入網(wǎng)址,http://localhost:8080/more, 就會(huì)進(jìn)入此頁(yè)面。
MultipartFile 需要修改為按照數(shù)組的方式去接收。
@PostMapping("/uploadMore")
public String moreFileUpload(@RequestParam("file") MultipartFile[] files,
RedirectAttributes redirectAttributes) {
if (files.length==0) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:uploadStatus";
}
for(MultipartFile file:files){
try {
byte[] bytes = file.getBytes();
Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
Files.write(path, bytes);
} catch (IOException e) {
e.printStackTrace();
}
}
redirectAttributes.addFlashAttribute("message", "You successfully uploaded all");
return "redirect:/uploadStatus";
}同樣是先判斷數(shù)組是否為空,在循環(huán)遍歷數(shù)組內(nèi)容將文件寫入到指定目錄下。在瀏覽器中輸入網(wǎng)址 http://localhost:8080/more, 選擇三個(gè)文件進(jìn)行測(cè)試,當(dāng)頁(yè)面出現(xiàn)以下信息時(shí)表示上傳成功。
Spring Boot - Upload Status You successfully uploaded all
以上就是SpringBoot中怎么利用Thymeleaf上傳文件,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過這篇文章學(xué)到更多知識(shí)。更多詳情敬請(qǐng)關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
文章名稱:SpringBoot中怎么利用Thymeleaf上傳文件
標(biāo)題URL:http://chinadenli.net/article34/pphise.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供做網(wǎng)站、網(wǎng)站改版、微信小程序、服務(wù)器托管、全網(wǎng)營(yíng)銷推廣、網(wǎng)頁(yè)設(shè)計(jì)公司
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
網(wǎng)頁(yè)設(shè)計(jì)公司知識(shí)