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

方式一:返回字節(jié)數(shù)組
可以通過下面這種方式,讀取文件(注意文件路徑,從 resources 開始),返回給前端文件的字節(jié)數(shù)組
@GetMapping("/get-template-1")
public byte[] getTemplate() throws IOException {
// 1.獲取文件
ClassPathResource resource = new ClassPathResource("template/excel/full/學(xué)生信息模板-填充.xlsx");
// 2.構(gòu)建響應(yīng)頭
String fileName = "學(xué)生信息模板.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>
方式二:寫入到響應(yīng)中
也可以用下面這種方式,將文件流寫入到響應(yīng)對象中
@GetMapping("/get-template-2")
public void getTemplate2(HttpServletResponse response) throws IOException {
// 1.獲取文件
ClassPathResource resource = new ClassPathResource("template/excel/full/學(xué)生信息模板-填充.xlsx");
// 2.構(gòu)建響應(yīng)頭
String fileName = "學(xué)生信息模板.xlsx";
String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);
// 3.寫入到響應(yīng)對象中
try (InputStream inputStream = resource.getInputStream();
OutputStream outputStream = response.getOutputStream()) {
inputStream.transferTo(outputStream);
outputStream.flush();
}
}
以上兩種方式都能將后端靜態(tài)資源返回給前端

到此這篇關(guān)于SpringBoot獲取resources目錄下靜態(tài)資源的兩種方式的文章就介紹到這了,更多相關(guān)SpringBoot獲取resources靜態(tài)資源內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
java自定義日志輸出文件(log4j日志文件輸出多個自定義日志文件)
打印日志的在程序中是必不可少的,如果需要將不同的日志打印到不同的地方,則需要定義不同的Appender,然后定義每一個Appender的日志級別、打印形式和日志的輸出路徑,下面看一個示例吧2014-01-01
springboot如何獲取application.yml里值的方法
這篇文章主要介紹了springboot如何獲取application.yml里的值,文章圍繞主題相關(guān)自資料展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-04-04
利用Mybatis自定義排序規(guī)則實(shí)現(xiàn)復(fù)雜排序
本文主要介紹了利用Mybatis自定義排序規(guī)則實(shí)現(xiàn)復(fù)雜排序,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2025-09-09
Spring?boot自定義加密解密數(shù)據(jù)庫連接配置示例代碼
在Spring Boot項(xiàng)目中,為了保護(hù)數(shù)據(jù)庫連接信息的安全,通常需要對敏感信息進(jìn)行加密,這篇文章主要介紹了Spring?boot自定義加密解密數(shù)據(jù)庫連接配置的相關(guān)資料,需要的朋友可以參考下2026-05-05

