SpringBoot中怎么利用Thymeleaf上傳文件

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

創(chuàng)新互聯(lián)專注于安陽企業(yè)網(wǎng)站建設(shè),成都響應(yīng)式網(wǎng)站建設(shè)公司,商城網(wǎng)站制作。安陽網(wǎng)站建設(shè)公司,為安陽等地區(qū)提供建站服務(wù)。全流程定制網(wǎng)站建設(shè),專業(yè)設(shè)計(jì),全程項(xiàng)目跟蹤,創(chuàng)新互聯(lián)專業(yè)和態(tài)度為您提供的服務(wù)

  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
#文件請(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í)懶加載

  1. 啟動(dòng)類

@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>
  • 非常簡(jiǎn)單的一個(gè) Post 請(qǐng)求,一個(gè)選擇框選擇文件、一個(gè)提交按鈕,效果如下: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 自動(dòng)跳轉(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 文件本地存儲(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é)果頁并給出提示;如果不為空讀取文件流并寫入到指定目錄,最后將結(jié)果展示到頁面。最常用的是最后兩個(gè)配置內(nèi)容,限制文件上傳大小,上傳時(shí)超過大小會(huì)拋出異常:

SpringBoot中怎么利用Thymeleaf上傳文件

當(dāng)然在真實(shí)的項(xiàng)目中我們可以在業(yè)務(wù)中會(huì)首先對(duì)文件大小進(jìn)行判斷,再將返回信息展示到頁面。

  1. 異常處理

這里演示的是 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";
    }
}

二、上傳多個(gè)文件

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

  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. 后臺(tái)處理

后端添加頁面訪問入口:

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

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

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)頁面出現(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://m.kartarina.com/article34/pphise.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供做網(wǎng)站網(wǎng)站改版微信小程序服務(wù)器托管全網(wǎng)營銷推廣網(wǎng)頁設(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)站建設(shè)
主站蜘蛛池模板: 无码视频在线观看| 国产av永久无码天堂影院| 亚欧无码精品无码有性视频| 亚洲精品无码久久久久A片苍井空 亚洲精品无码久久久久YW | 中文午夜乱理片无码| 国产产无码乱码精品久久鸭| 久久久久精品国产亚洲AV无码| 青青爽无码视频在线观看| 中文字幕无码免费久久| 无码中文人妻在线一区二区三区 | 亚洲AV永久无码区成人网站| 亚洲日韩国产精品无码av| 亚洲精品国产日韩无码AV永久免费网| 日韩精品无码一区二区中文字幕 | 无码专区天天躁天天躁在线| 亚洲美日韩Av中文字幕无码久久久妻妇| 久久久无码一区二区三区| 国产成年无码AV片在线韩国| 小泽玛丽无码视频一区| 男人av无码天堂| 亚洲精品无码你懂的| 69久久精品无码一区二区| 无码人妻丰满熟妇精品区| 久久久国产精品无码免费专区| 亚洲AV无码不卡在线观看下载| 国产品无码一区二区三区在线| 无码夫の前で人妻を犯す中字| 久久无码专区国产精品发布 | 亚洲中文字幕无码中文字| 亚洲av中文无码乱人伦在线r▽| 亚洲中文字幕无码一区| 国产成人无码AV一区二区| 国产在线精品无码二区| 中文无码人妻有码人妻中文字幕| 五月婷婷无码观看| 免费无遮挡无码视频在线观看| 日韩AV无码不卡网站| 成在线人免费无码高潮喷水| 国产av激情无码久久| 亚洲&#228;v永久无码精品天堂久久| 无码视频在线播放一二三区|