Spring Boot中進(jìn)行 文件上傳和 文件下載功能實(shí)現(xiàn)
一、SpringBoot中進(jìn)行 " 文件上傳" :
開(kāi)發(fā)Wb應(yīng)用時(shí),文件上傳是很常見(jiàn)的一個(gè)需求,瀏覽器 通過(guò) 表單形式 將 文件 以 流的形式傳遞 給 服務(wù)器,服務(wù)器再對(duì)上傳的數(shù)據(jù)解析處理。下面將通過(guò)一個(gè)案例講解使用 SpringBoot 實(shí)現(xiàn) 文件上傳,具體步驟 如下 :
1.編寫 “文件上傳” 的 “表單頁(yè)面”
在項(xiàng)目的 templates模板引擎文件夾下創(chuàng)建一個(gè)用來(lái)上傳文件的upload.html模板頁(yè)面 :
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>動(dòng)態(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的頁(yè)面緩存設(shè)置(默認(rèn)為true),開(kāi)發(fā)中為方便調(diào)試應(yīng)設(shè)置為false,上線穩(wěn)定后應(yīng)保持默認(rèn)true spring.thymeleaf.cache=false ##配置國(guó)際化文件基礎(chǔ)名 #spring.messages.basename=i18n.login #單個(gè)文件上傳大小限制(默認(rèn)為1MB) spring.servlet.multipart.max-file-size=10MB #總文件上傳大小限制 spring.servlet.multipart.max-request-size=50MB
在 application.properties 全局配置文件中,對(duì)文件 上傳過(guò)程中的上傳大小進(jìn)行了設(shè)置。
3.進(jìn)行文件上傳處理,實(shí)現(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 + 原始文件名 來(lái)生成一個(gè)新的文件名
fileName = UUID.randomUUID()+"_"+fileName;
//指定文件上傳的本地存儲(chǔ)目錄,不存在則提前創(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)到文件上傳頁(yè)面
return "upload";
}
}4.效果測(cè)試
啟動(dòng)項(xiàng)目,在瀏覽器訪問(wèn) http://localhost:8080/toUpload ,效果如下圖所示 :



通過(guò)以上圖片可以看出,SpringBoot 中進(jìn)行 “文件上傳”成功 。
二、SpringBoot中進(jìn)行 “文件下載” :
下載文件能夠通過(guò)IO流實(shí)現(xiàn),所以 多數(shù)框架并沒(méi)有對(duì)文件下載進(jìn)行封裝處理。文件下載時(shí)涉及不同瀏覽器的解析處理,可能會(huì)出現(xiàn) 中文亂碼 的情況。
接下來(lái)將針對(duì) 下載英文名文件 和 中文名文件 進(jìn)行講解。
“英文名稱” 文件下載 : 1.添加文件下載工具依賴
在 pom.xml文件中引入文件下載的一個(gè)工具依賴 :
<!-- 文件下載的工具依賴 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>2.定制文件下載頁(yè)面
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>上面代碼中通過(guò)列表展示了要下載的兩個(gè) 文件名及其下載鏈接。需要注意的是,在文件下載之前,需要保證在文件下載目錄(本示例中的“S:\File”目錄)中存在對(duì)應(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)建該文件對(duì)象
File file = new File(dirPath + File.separator + filename);
//設(shè)置響應(yīng)頭
HttpHeaders headers = new HttpHeaders();
//通知瀏覽器以下載方式打開(kāi)
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.效果測(cè)試
啟動(dòng)項(xiàng)目,在瀏覽器訪問(wèn) http://localhost:8080/toDownload ,效果如下圖所示 :


“中文名稱” 文件下載 : 1.添加文件下載工具依賴
在 pom.xml文件中引入文件下載的一個(gè)工具依賴 :
<!-- 文件下載的工具依賴 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>2.定制文件下載頁(yè)面
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>上面代碼中通過(guò)列表展示了要下載的兩個(gè) 文件名及其下載鏈接。需要注意的是,在文件下載之前,需要保證在文件下載目錄(本示例中的“S:\File”目錄)中存在對(duì)應(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)建該文件對(duì)象
File file = new File(dirPath + File.separator + filename);
//設(shè)置響應(yīng)頭
HttpHeaders headers = new HttpHeaders();
//通知瀏覽器以下載方式打開(kāi)(下載前對(duì)文件名進(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"};
//獲取請(qǐng)求頭代理信息
String userAgent = request.getHeader("User-Agent");
for (String keyWord : IEBrowserKeyWords) {
if (userAgent.contains(keyWord)) {
//IE內(nèi)核瀏覽器,統(tǒng)一為UTF-8編碼顯示,并對(duì)轉(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.效果測(cè)試
啟動(dòng)項(xiàng)目,在瀏覽器訪問(wèn) http://localhost:8080/toDownload ,效果如下圖所示 :


到此這篇關(guān)于Spring Boot中進(jìn)行 “文件上傳” 和 “文件下載”的文章就介紹到這了,更多相關(guān)Spring Boot文件上傳和 文件下載內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SpringBoot+ruoyi框架文件上傳和下載的實(shí)現(xiàn)
- SpringBoot中的文件上傳和異常處理詳解
- SpringBoot實(shí)現(xiàn)文件上傳下載實(shí)時(shí)進(jìn)度條功能(附源碼)
- SpringBoot簡(jiǎn)單實(shí)現(xiàn)文件上傳
- SpringBoot實(shí)現(xiàn)文件下載功能的方式分享
- vue+element+springboot實(shí)現(xiàn)文件下載進(jìn)度條展現(xiàn)功能示例
- springboot中Excel文件下載踩坑大全
- springboot單文件下載和多文件壓縮zip下載的實(shí)現(xiàn)
- 在 Spring Boot 項(xiàng)目中實(shí)現(xiàn)文件下載功能
相關(guān)文章
SpringBoot實(shí)現(xiàn)國(guó)際化i18n詳解
國(guó)際化(Internationalization,簡(jiǎn)稱i18n)是指在軟件應(yīng)用中支持多種語(yǔ)言和文化的能力,本文將介紹如何在Spring?Boot應(yīng)用中實(shí)現(xiàn)國(guó)際化,需要的可以參考下2024-12-12
IDEA JarEditor編輯jar包方式(直接新增,修改,刪除jar包內(nèi)的class文件)
文章主要介紹了如何使用IDEA的JarEditor插件直接修改jar包內(nèi)的class文件,而不需要手動(dòng)解壓、反編譯和重新打包,通過(guò)該插件,可以更方便地進(jìn)行jar包的修改和測(cè)試2025-01-01
Java?集合框架底層數(shù)據(jù)結(jié)構(gòu)實(shí)現(xiàn)深度解析(示例詳解)
Java 集合框架(Java Collections Framework, JCF)是支撐高效數(shù)據(jù)處理的核心組件,其底層數(shù)據(jù)結(jié)構(gòu)的設(shè)計(jì)直接影響性能與適用場(chǎng)景,這篇文章主要介紹Java集合框架底層數(shù)據(jù)結(jié)構(gòu)實(shí)現(xiàn)深度解析,需要的朋友可以參考下2025-06-06
idea日志亂碼和tomcat日志亂碼問(wèn)題的解決方法
這篇文章主要介紹了idea日志亂碼和tomcat日志亂碼問(wèn)題的解決方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-08-08
maven profile自動(dòng)切換環(huán)境參數(shù)的2種方法詳解
這篇文章主要給大家介紹了關(guān)于maven profile自動(dòng)切換環(huán)境參數(shù)的2種方法,文中通過(guò)示例代碼將這兩種方法介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2018-04-04
一文講解如何解決Java中的IllegalArgumentException異常
這篇文章主要給大家介紹了關(guān)于如何解決Java中IllegalArgumentException異常的相關(guān)資料,IllegalArgumentException是Java中的一個(gè)標(biāo)準(zhǔn)異常類,通常在方法接收到一個(gè)不合法的參數(shù)時(shí)拋出,需要的朋友可以參考下2024-03-03
Java中的StackOverflowError從原理到實(shí)戰(zhàn)指南(棧溢出的 4 種典型場(chǎng)景)
java.lang.StackOverflowError 是 JVM 拋出的錯(cuò)誤(Error) ,不是普通異常(Exception),本文給大家介紹Java中的StackOverflowError從原理到實(shí)戰(zhàn)指南(棧溢出的 4 種典型場(chǎng)景),感興趣的朋友跟隨小編一起看看吧2026-03-03
SpringBoot項(xiàng)目使用MDC給日志增加唯一標(biāo)識(shí)的實(shí)現(xiàn)步驟
本文介紹了如何在SpringBoot項(xiàng)目中使用MDC(Mapped?Diagnostic?Context)為日志增加唯一標(biāo)識(shí),以便于日志追蹤,通過(guò)創(chuàng)建日志攔截器、配置攔截器以及修改日志配置文件,可以實(shí)現(xiàn)這一功能,文章還提供了源碼地址,方便讀者學(xué)習(xí)和參考,感興趣的朋友一起看看吧2025-03-03

