Spring Boot中進行 文件上傳和 文件下載功能實現
一、SpringBoot中進行 " 文件上傳" :
開發(fā)Wb應用時,文件上傳是很常見的一個需求,瀏覽器 通過 表單形式 將 文件 以 流的形式傳遞 給 服務器,服務器再對上傳的數據解析處理。下面將通過一個案例講解使用 SpringBoot 實現 文件上傳,具體步驟 如下 :
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.在全局配置文件中添加文件上傳的相關配置
在 全局配置文件 : application.properties中添加文件上傳的相關設置,配置如下 :
application.properties :
spring.application.name=chapter_12 #thymeleaf的頁面緩存設置(默認為true),開發(fā)中為方便調試應設置為false,上線穩(wěn)定后應保持默認true spring.thymeleaf.cache=false ##配置國際化文件基礎名 #spring.messages.basename=i18n.login #單個文件上傳大小限制(默認為1MB) spring.servlet.multipart.max-file-size=10MB #總文件上傳大小限制 spring.servlet.multipart.max-request-size=50MB
在 application.properties 全局配置文件中,對文件 上傳過程中的上傳大小進行了設置。
3.進行文件上傳處理,實現 “文件上傳” 功能
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 { //關于File的controller類
@GetMapping("/toUpload")
public String toUpload(){
return "upload";
}
@PostMapping("/uploadFile")
public String uploadFile(MultipartFile[] fileUpload, Model model) {
//默認文件上傳成功,并返回狀態(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)信息回調到文件上傳頁面
return "upload";
}
}4.效果測試
啟動項目,在瀏覽器訪問 http://localhost:8080/toUpload ,效果如下圖所示 :



通過以上圖片可以看出,SpringBoot 中進行 “文件上傳”成功 。
二、SpringBoot中進行 “文件下載” :
下載文件能夠通過IO流實現,所以 多數框架并沒有對文件下載進行封裝處理。文件下載時涉及不同瀏覽器的解析處理,可能會出現 中文亂碼 的情況。
接下來將針對 下載英文名文件 和 中文名文件 進行講解。
“英文名稱” 文件下載 : 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”目錄)中存在對應的文件,可以自行存放,只要 保持文件名統一 即可。
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 { //關于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);
//設置響應頭
HttpHeaders headers = new HttpHeaders();
//通知瀏覽器以下載方式打開
headers.setContentDispositionFormData("attachment",filename);
//定義以流的形式下載返回文件數據
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”目錄)中存在對應的文件,可以自行存放,只要 保持文件名統一 即可。
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 { //關于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);
//設置響應頭
HttpHeaders headers = new HttpHeaders();
//通知瀏覽器以下載方式打開(下載前對文件名進行轉碼)
filename=getFilename(request,filename);
headers.setContentDispositionFormData("attachment",filename);
//定義以流的形式下載返回文件數據
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);
}
}
//根據瀏覽器的不同進行編碼設置,返回編碼后的文件名
private String getFilename(HttpServletRequest request,String filename)
throws Exception {
//IE不同版本User-Agent中出現的關鍵詞
String[] IEBrowserKeyWords = {"MSIE", "Trident", "Edge"};
//獲取請求頭代理信息
String userAgent = request.getHeader("User-Agent");
for (String keyWord : IEBrowserKeyWords) {
if (userAgent.contains(keyWord)) {
//IE內核瀏覽器,統一為UTF-8編碼顯示,并對轉換的+進行更正
return URLEncoder.encode(filename, "UTF-8").replace("+"," ");
}}
//火狐等其他瀏覽器統一為ISO-8859-1編碼顯示
return new String(filename.getBytes("UTF-8"), "ISO-8859-1");
}
}4.效果測試
啟動項目,在瀏覽器訪問 http://localhost:8080/toDownload ,效果如下圖所示 :


到此這篇關于Spring Boot中進行 “文件上傳” 和 “文件下載”的文章就介紹到這了,更多相關Spring Boot文件上傳和 文件下載內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
java.lang.UnsupportedOperationException的問題解決
本文主要介紹了java.lang.UnsupportedOperationException的問題解決,該錯誤表示調用的方法不被支持或不可用,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2024-07-07
Java ArrayList與LinkedList及HashMap容器的用法區(qū)別
這篇文章主要介紹了Java ArrayList與LinkedList及HashMap容器的用法區(qū)別,具有一定的參考價值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-07-07
springboot加載復雜的yml文件獲取不到值的解決方案
這篇文章主要介紹了springboot加載復雜的yml文件獲取不到值的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-03-03

