溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

SpringBoot中怎么利用Thymeleaf上傳文件

發(fā)布時間:2021-06-15 14:01:35 來源:億速云 閱讀:276 作者:Leah 欄目:大數(shù)據(jù)

本篇文章給大家分享的是有關(guān)SpringBoot中怎么利用Thymeleaf上傳文件,小編覺得挺實用的,因此分享給大家學習,希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。


  1. 添加依賴包

<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 做頁面模板引擎。

  1. 配置信息

常用配置內(nèi)容,單位支持 MB 或者 KB:

#支持的最大文件
spring.servlet.multipart.max-file-size=100MB
#文件請求最大限制
spring.servlet.multipart.max-request-size=100MB

以上配置主要是通過設(shè)置 MultipartFile 的屬性來控制上傳限制,MultipartFile 是 Spring 上傳文件的封裝類,包含了文件的二進制流和文件屬性等信息,在配置文件中也可對相關(guān)屬性進行配置。

除過以上配置,常用的配置信息如下:

  • spring.servlet.multipart.enabled=true,是否支持 multipart 上傳文件

  • spring.servlet.multipart.file-size-threshold=0,支持文件寫入磁盤

  • spring.servlet.multipart.location=,上傳文件的臨時目錄

  • spring.servlet.multipart.max-file-size=10Mb,最大支持文件大小

  • spring.servlet.multipart.max-request-sizee=10Mb,最大支持請求大小

  • spring.servlet.multipart.resolve-lazily=false,是否支持 multipart 上傳文件時懶加載

  1. 啟動類

@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 也捕獲不到。 SpringBoot中怎么利用Thymeleaf上傳文件

  1. 編寫前端頁面

  • 上傳頁面:

<!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>
  • 非常簡單的一個 Post 請求,一個選擇框選擇文件、一個提交按鈕,效果如下: SpringBoot中怎么利用Thymeleaf上傳文件

  • 上傳結(jié)果展示頁面:

<!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>
  • 效果圖如下:

SpringBoot中怎么利用Thymeleaf上傳文件

  1. 編寫上傳控制類

  • 訪問 localhost:8080 自動跳轉(zhuǎn)到上傳頁面:

@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 文件本地存儲地址
        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é)果頁并給出提示;如果不為空讀取文件流并寫入到指定目錄,最后將結(jié)果展示到頁面。最常用的是最后兩個配置內(nèi)容,限制文件上傳大小,上傳時超過大小會拋出異常:

SpringBoot中怎么利用Thymeleaf上傳文件

當然在真實的項目中我們可以在業(yè)務(wù)中會首先對文件大小進行判斷,再將返回信息展示到頁面。

  1. 異常處理

這里演示的是 MultipartException 的異常處理,也可以稍微改造監(jiān)控整個項目的異常問題。

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(MultipartException.class)
    public String handleError1(MultipartException e, RedirectAttributes redirectAttributes) {
        redirectAttributes.addFlashAttribute("message", e.getCause().getMessage());
        return "redirect:/uploadStatus";
    }
}

二、上傳多個文件

在項目中經(jīng)常會有一次性上傳多個文件的需求,我們稍作修改即可支持。

  1. 前端頁面

首先添加可以支持上傳多文件的頁面,內(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>
  1. 后臺處理

后端添加頁面訪問入口:

@GetMapping("/more")
public String uploadMore() {
    return "uploadMore";
}

在瀏覽器中輸入網(wǎng)址,http://localhost:8080/more, 就會進入此頁面。

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, 選擇三個文件進行測試,當頁面出現(xiàn)以下信息時表示上傳成功。

Spring Boot - Upload Status
You successfully uploaded all

以上就是SpringBoot中怎么利用Thymeleaf上傳文件,小編相信有部分知識點可能是我們?nèi)粘9ぷ鲿姷交蛴玫降摹OM隳芡ㄟ^這篇文章學到更多知識。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI