大战熟女丰满人妻av-荡女精品导航-岛国aaaa级午夜福利片-岛国av动作片在线观看-岛国av无码免费无禁网站-岛国大片激情做爰视频

專注Java教育14年 全國咨詢/投訴熱線:400-8080-105
動力節(jié)點(diǎn)LOGO圖
始于2009,口口相傳的Java黃埔軍校
首頁 hot資訊 使用SpringBoot文件上傳示例

使用SpringBoot文件上傳示例

更新時(shí)間:2021-12-29 11:08:48 來源:動力節(jié)點(diǎn) 瀏覽2288次

上傳文件是互聯(lián)網(wǎng)中常常應(yīng)用的場景之一,最典型的情況就是上傳頭像等,今天就帶著帶著大家做一個 Spring Boot 上傳文件的小案例。

1.pom 包配置

我們使用 Spring Boot 版本 2.1.0、jdk 1.8、tomcat 8.0。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.0.RELEASE</version>
</parent>
<properties>
    <java.version>1.8</java.version>
</properties>
<dependencies>
    <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>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <optional>true</optional>
    </dependency>
</dependencies>

引入了spring-boot-starter-thymeleaf做頁面模板引擎,寫一些簡單的上傳示例。

2.啟動類設(shè)置

@SpringBootApplication
public class FileUploadWebApplication {
    public static void main(String[] args) throws Exception {
        SpringApplication.run(FileUploadWebApplication.class, args);
    }
    @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;
    }
}

tomcatEmbedded 這段代碼是為了解決,上傳文件大于10M出現(xiàn)連接重置的問題。此異常內(nèi)容 GlobalException 也捕獲不到。

3.編寫前端頁面

上傳頁面

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Spring Boot file upload example</h1>
<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 請求,一個選擇框選擇文件,一個提交按鈕,效果如下:

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

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<body>
<h1>Spring Boot - Upload Status</h1>
<div th:if="${message}">
    <h2 th:text="${message}"/>
</div>
</body>
</html>

效果圖如下:

4.編寫上傳控制類

訪問 localhost 自動跳轉(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();
        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é)果展示到頁面。

MultipartFile是Spring上傳文件的封裝類,包含了文件的二進(jìn)制流和文件屬性等信息,在配置文件中也可對相關(guān)屬性進(jìn)行配置,基本的配置信息如下:

spring.http.multipart.enabled=true #默認(rèn)支持文件上傳.

spring.http.multipart.file-size-threshold=0 #支持文件寫入磁盤.

spring.http.multipart.location= # 上傳文件的臨時(shí)目錄

spring.http.multipart.max-file-size=1Mb # 最大支持文件大小

spring.http.multipart.max-request-size=10Mb # 最大支持請求大小

最常用的是最后兩個配置內(nèi)容,限制文件上傳大小,上傳時(shí)超過大小會拋出異常:

5.異常處理

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

設(shè)置一個@ControllerAdvice用來監(jiān)控Multipart上傳的文件大小是否受限,當(dāng)出現(xiàn)此異常時(shí)在前端頁面給出提示。利用@ControllerAdvice可以做很多東西,比如全局的統(tǒng)一異常處理等,感興趣的同學(xué)可以下來了解。

提交申請后,顧問老師會電話與您溝通安排學(xué)習(xí)

免費(fèi)課程推薦 >>
技術(shù)文檔推薦 >>
主站蜘蛛池模板: www伊人 | 在线播放免费一级毛片欧美 | 免费在线观看黄色的网站 | 免费精品久久久视频 | 久久久精品免费热线观看 | 97在线观看成人免费视频 | 欧美日韩亚洲精品国产色 | 亚洲精品国产美女在线观看 | 香蕉视频国产精品 | 99热久久精品免费精品 | 欧美精品xxx| 69成人做爰视频在线观看 | 精品国产乱码一区二区三区 | 亚洲大片免费 | 中国护士一级毛片免费版本 | 国产香蕉视频在线 | 色狠狠一区二区 | 98在线视频噜噜噜国产 | 日日夜夜天天操 | 91精品国产91久久久久 | 久久综合色之久久综合 | 免费播放欧美毛片欧美aaaaa | 完整日本特级毛片 | 成人毛片免费视频播放 | 亚洲 欧美精品 | 婷综合 | 国产一区二区三区四区在线观看 | 国产日韩一区二区 | 成人合集大片bd高清在线观看 | 国产小视频免费观看 | 91久草视频| 久久中文娱乐网 | 香蕉久草在线 | 一级毛片一级毛片一级毛片 | 天天躁夜夜躁很很躁麻豆 | 欧美视频在线观看一区二区 | 亚欧有色亚欧乱色视频 | 亚洲国产男人本色在线观看的a站 | 综合 欧美 国产 视频二区 | 国产伦一区二区三区免费 | 狠狠干奇米 |