Spring Boot中進(jìn)行 文件上傳和 文件下載功能實現(xiàn)
一、SpringBoot中進(jìn)行 " 文件上傳" :
開發(fā)Wb應(yīng)用時,文件上傳是很常見的一個需求,瀏覽器 通過 表單形式 將 文件 以 流的形式傳遞 給 服務(wù)器,服務(wù)器再對上傳的數(shù)據(jù)解析處理。下面將通過一個案例講解使用 SpringBoot 實現(xiàn) 文件上傳,具體步驟 如下 :
1.編寫 “文件上傳” 的 “表單頁面”
在項目的 templates模板引擎文件夾下創(chuàng)建一個用來上傳文件的upload.html模板頁面 :
upload.html :
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>動態(tài)添加文件上傳列表</title> <link th:href="@{/login/css/bootstrap.min.css}" rel="external nofollow" rel="stylesheet"> <script th:src="@{/login/js/jquery-3.7.1.min.js}"></script> </head> <body> <div th:if="${uploadStatus}" style="color: red" th:text="${uploadStatus}"> 上傳成功</div> <form th:action="@{/uploadFile}" method="post" enctype="multipart/form-data"> 上傳文件: <input type="button" value="添加文件" onclick="add()"/> <div id="file" style="margin-top: 10px;" th:value="文件上傳區(qū)域"> </div> <input id="submit" type="submit" value="上傳" style="display: none;margin-top: 10px;"/> </form> <script type="text/javascript"> function add(){ var innerdiv = "<div>"; innerdiv += "<input type='file' name='fileUpload' required='required'>" + "<input type='button' value='刪除' οnclick='remove(this)'>"; innerdiv +="</div>"; $("#file").append(innerdiv); $("#submit").css("display","block"); } function remove(obj) { $(obj).parent().remove(); if($("#file div").length ==0){ $("#submit").css("display","none"); } } </script> </body> </html>
2.在全局配置文件中添加文件上傳的相關(guān)配置
在 全局配置文件 : application.properties中添加文件上傳的相關(guān)設(shè)置,配置如下 :
application.properties :
spring.application.name=chapter_12 #thymeleaf的頁面緩存設(shè)置(默認(rèn)為true),開發(fā)中為方便調(diào)試應(yīng)設(shè)置為false,上線穩(wěn)定后應(yīng)保持默認(rèn)true spring.thymeleaf.cache=false ##配置國際化文件基礎(chǔ)名 #spring.messages.basename=i18n.login #單個文件上傳大小限制(默認(rèn)為1MB) spring.servlet.multipart.max-file-size=10MB #總文件上傳大小限制 spring.servlet.multipart.max-request-size=50MB
在 application.properties 全局配置文件中,對文件 上傳過程中的上傳大小進(jìn)行了設(shè)置。
3.進(jìn)行文件上傳處理,實現(xiàn) “文件上傳” 功能
FileController.java :
package com.myh.chapter_12.controller; import org.springframework.boot.Banner; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.util.UUID; /** * 文件管理控制類 */ @Controller //加入到IOC容器中 public class FileController { //關(guān)于File的controller類 @GetMapping("/toUpload") public String toUpload(){ return "upload"; } @PostMapping("/uploadFile") public String uploadFile(MultipartFile[] fileUpload, Model model) { //默認(rèn)文件上傳成功,并返回狀態(tài)信息 model.addAttribute("uploadStatus", "上傳成功!"); for (MultipartFile file : fileUpload) { //獲取文件名以及后綴名 (獲取原始文件名) String fileName = file.getOriginalFilename(); //使用UUID + 原始文件名 來生成一個新的文件名 fileName = UUID.randomUUID()+"_"+fileName; //指定文件上傳的本地存儲目錄,不存在則提前創(chuàng)建 String dirPath = "S:\\File\\"; File filePath = new File(dirPath); if(!filePath.exists()){filePath.mkdirs();}//創(chuàng)建該目錄 try { //執(zhí)行“文件上傳”的方法 file.transferTo(new File(dirPath+fileName)); } catch (Exception e) {e.printStackTrace(); //上傳失敗,返回失敗信息 model.addAttribute("uploadStatus","上傳失?。?"+e.getMessage());} } //攜帶狀態(tài)信息回調(diào)到文件上傳頁面 return "upload"; } }
4.效果測試
啟動項目,在瀏覽器訪問 http://localhost:8080/toUpload ,效果如下圖所示 :
通過以上圖片可以看出,SpringBoot 中進(jìn)行 “文件上傳”成功 。
二、SpringBoot中進(jìn)行 “文件下載” :
下載文件能夠通過IO流實現(xiàn),所以 多數(shù)框架并沒有對文件下載進(jìn)行封裝處理。文件下載時涉及不同瀏覽器的解析處理,可能會出現(xiàn) 中文亂碼 的情況。
接下來將針對 下載英文名文件 和 中文名文件 進(jìn)行講解。
“英文名稱” 文件下載 : 1.添加文件下載工具依賴
在 pom.xml文件中引入文件下載的一個工具依賴 :
<!-- 文件下載的工具依賴 --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency>
2.定制文件下載頁面
download.html :
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>"英文名稱"文件下載</title></head><body> <div style="margin-bottom: 10px">文件下載列表:</div> <table> <tr> <td>嘻嘻哈哈123.txt</td> <td><a th:href="@{/download(filename='5afa8ee7-6cbf-4632-9965-4df31aad4558_嘻嘻哈哈123456.txt')}" rel="external nofollow" >下載該文件</a></td> </tr> <tr> <td>嘻嘻哈哈123456.txt</td> <td><a th:href="@{/download(filename='c53a27b1-b42e-41a4-b283-86ac43034203_嘻嘻哈哈123.txt')}" rel="external nofollow" >下載該文件</a></td> </tr> </table> </body> </html>
上面代碼中通過列表展示了要下載的兩個 文件名及其下載鏈接。需要注意的是,在文件下載之前,需要保證在文件下載目錄(本示例中的“S:\File”目錄)中存在對應(yīng)的文件,可以自行存放,只要 保持文件名統(tǒng)一 即可。
3.編寫文件下載處理方法
FileController.java :
package com.myh.chapter_12.controller; import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.springframework.boot.Banner; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.net.URLEncoder; import java.util.UUID; /** * 文件管理控制類 */ @Controller //加入到IOC容器中 public class FileController { //關(guān)于File的controller類 @GetMapping("/toDownload") public String toDownload(){ return "download"; } /** * 英文名稱文件下載 */ @GetMapping("/download") public ResponseEntity<byte[]> fileDownload(String filename){ //指定要下載的文件根路徑 String dirPath = "S:\\File\\"; //創(chuàng)建該文件對象 File file = new File(dirPath + File.separator + filename); //設(shè)置響應(yīng)頭 HttpHeaders headers = new HttpHeaders(); //通知瀏覽器以下載方式打開 headers.setContentDispositionFormData("attachment",filename); //定義以流的形式下載返回文件數(shù)據(jù) headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); try {return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);} catch (Exception e) {e.printStackTrace(); return new ResponseEntity<byte[]>(e.getMessage().getBytes(), HttpStatus.EXPECTATION_FAILED); } } }
4.效果測試
啟動項目,在瀏覽器訪問 http://localhost:8080/toDownload ,效果如下圖所示 :
“中文名稱” 文件下載 : 1.添加文件下載工具依賴
在 pom.xml文件中引入文件下載的一個工具依賴 :
<!-- 文件下載的工具依賴 --> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.6</version> </dependency>
2.定制文件下載頁面
download.html :
<!DOCTYPE html> <html lang="en" xmlns:th="http://www.thymeleaf.org"> <head> <meta charset="UTF-8"> <title>中文名稱文件下載</title></head><body> <div style="margin-bottom: 10px">文件下載列表:</div> <table> <tr> <td>嘻嘻哈哈123456.txt</td> <td><a th:href="@{/download(filename='708ebc14-2ca7-4b66-b0bf-3b9c65df6ec1_嘻嘻哈哈123456.txt')}" rel="external nofollow" >下載該文件</a></td> </tr> <tr> <td>嘻嘻哈哈123.txt</td> <td><a th:href="@{/download(filename='418b0e77-59dc-4697-8a62-6a450d466567_嘻嘻哈哈123.txt')}" rel="external nofollow" >下載該文件</a></td> </tr> </table> </body> </html>
上面代碼中通過列表展示了要下載的兩個 文件名及其下載鏈接。需要注意的是,在文件下載之前,需要保證在文件下載目錄(本示例中的“S:\File”目錄)中存在對應(yīng)的文件,可以自行存放,只要 保持文件名統(tǒng)一 即可。
3.編寫文件下載處理方法
FileController.java :
??????? package com.myh.chapter_12.controller; import jakarta.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.springframework.boot.Banner; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.net.URLEncoder; import java.util.UUID; /** * 文件管理控制類 */ @Controller //加入到IOC容器中 public class FileController { //關(guān)于File的controller類 @GetMapping("/toDownload") public String toDownload(){ return "download"; } /** * "中文名稱"文件下載 */ @GetMapping("/download") public ResponseEntity<byte[]> fileDownload(HttpServletRequest request,String filename) throws Exception{ //指定下載的文件根路徑 String dirPath = "S:\\File\\"; //創(chuàng)建該文件對象 File file = new File(dirPath + File.separator + filename); //設(shè)置響應(yīng)頭 HttpHeaders headers = new HttpHeaders(); //通知瀏覽器以下載方式打開(下載前對文件名進(jìn)行轉(zhuǎn)碼) filename=getFilename(request,filename); headers.setContentDispositionFormData("attachment",filename); //定義以流的形式下載返回文件數(shù)據(jù) headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); try {return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);} catch (Exception e) {e.printStackTrace(); return new ResponseEntity<byte[]>(e.getMessage().getBytes(), HttpStatus.EXPECTATION_FAILED); } } //根據(jù)瀏覽器的不同進(jìn)行編碼設(shè)置,返回編碼后的文件名 private String getFilename(HttpServletRequest request,String filename) throws Exception { //IE不同版本User-Agent中出現(xiàn)的關(guān)鍵詞 String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"}; //獲取請求頭代理信息 String userAgent = request.getHeader("User-Agent"); for (String keyWord : IEBrowserKeyWords) { if (userAgent.contains(keyWord)) { //IE內(nèi)核瀏覽器,統(tǒng)一為UTF-8編碼顯示,并對轉(zhuǎn)換的+進(jìn)行更正 return URLEncoder.encode(filename, "UTF-8").replace("+"," "); }} //火狐等其他瀏覽器統(tǒng)一為ISO-8859-1編碼顯示 return new String(filename.getBytes("UTF-8"), "ISO-8859-1"); } }
4.效果測試
啟動項目,在瀏覽器訪問 http://localhost:8080/toDownload ,效果如下圖所示 :
到此這篇關(guān)于Spring Boot中進(jìn)行 “文件上傳” 和 “文件下載”的文章就介紹到這了,更多相關(guān)Spring Boot文件上傳和 文件下載內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java.lang.UnsupportedOperationException的問題解決
本文主要介紹了java.lang.UnsupportedOperationException的問題解決,該錯誤表示調(diào)用的方法不被支持或不可用,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-07-07Java ArrayList與LinkedList及HashMap容器的用法區(qū)別
這篇文章主要介紹了Java ArrayList與LinkedList及HashMap容器的用法區(qū)別,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-07-07springboot加載復(fù)雜的yml文件獲取不到值的解決方案
這篇文章主要介紹了springboot加載復(fù)雜的yml文件獲取不到值的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03