SpringBoot獲取resources目錄下靜態(tài)資源的兩種方式
說明:本文介紹在 Spring Boot 項目中,獲取項目下靜態(tài)資源的兩種方式。
場景
一般來說,項目相關的靜態(tài)資源,都會放在當前模塊的 resources 目錄下,如下:

方式一:返回字節(jié)數(shù)組
可以通過下面這種方式,讀取文件(注意文件路徑,從 resources 開始),返回給前端文件的字節(jié)數(shù)組
@GetMapping("/get-template-1")
public byte[] getTemplate() throws IOException {
// 1.獲取文件
ClassPathResource resource = new ClassPathResource("template/excel/full/學生信息模板-填充.xlsx");
// 2.構建響應頭
String fileName = "學生信息模板.xlsx";
String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", encodedFileName);
// 3.返回
return ResponseEntity.ok()
.headers(headers)
.body(resource.getInputStream().readAllBytes()).getBody();
}
這種方式,需要編譯環(huán)境是 Java 10(包括10) 以上的,不然編譯不通過

在 pom 文件末尾定義編譯環(huán)境(大于或等于10)
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>17</source>
<target>17</target>
</configuration>
</plugin>
</plugins>
</build>
方式二:寫入到響應中
也可以用下面這種方式,將文件流寫入到響應對象中
@GetMapping("/get-template-2")
public void getTemplate2(HttpServletResponse response) throws IOException {
// 1.獲取文件
ClassPathResource resource = new ClassPathResource("template/excel/full/學生信息模板-填充.xlsx");
// 2.構建響應頭
String fileName = "學生信息模板.xlsx";
String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);
// 3.寫入到響應對象中
try (InputStream inputStream = resource.getInputStream();
OutputStream outputStream = response.getOutputStream()) {
inputStream.transferTo(outputStream);
outputStream.flush();
}
}
以上兩種方式都能將后端靜態(tài)資源返回給前端

到此這篇關于SpringBoot獲取resources目錄下靜態(tài)資源的兩種方式的文章就介紹到這了,更多相關SpringBoot獲取resources靜態(tài)資源內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
SpringBoot基于token防止訂單重復創(chuàng)建
本文主要介紹了SpringBoot基于token防止訂單重復創(chuàng)建,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2025-06-06
JAVA的LIST接口的REMOVE重載方法調(diào)用原理解析
這篇文章主要介紹了JAVA的LIST接口的REMOVE重載方法調(diào)用原理解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2019-10-10
SpringBoot+Beetl實現(xiàn)動態(tài)數(shù)據(jù)庫DDL的示例代碼
最近公司里有一個新的需求,需要導出數(shù)據(jù)庫元數(shù)據(jù)表中存儲的表的 DDL 語句,而在元數(shù)據(jù)表中數(shù)據(jù)源的類型龐大,少則十幾種多則達到幾十種,各種數(shù)據(jù)庫類型都有,本篇文章就從這個模版引擎來入手介紹如何實現(xiàn)功能,需要的朋友可以參考下2025-06-06

