Spring Boot應(yīng)用實現(xiàn)圖片資源服務(wù)的方法
在這篇文章中,我們將介紹如何使用Spring Boot創(chuàng)建一個REST API來提供服務(wù)器上的靜態(tài)圖片資源。該API包括路徑安全檢查、文件存在性驗證以及緩存控制等功能,并且代碼包含詳細的注釋以幫助理解。
Maven依賴
首先,在您的pom.xml文件中添加以下依賴項:
<dependencies>
<!-- Spring Boot Starter Web for building web applications -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!-- Lombok to reduce boilerplate code -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<scope>provided</scope>
</dependency>
<!-- For logging -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
</dependencies>確保您已經(jīng)正確配置了Maven項目的其他部分,如<parent>標簽和版本管理等。
Java代碼
接下來是核心Java代碼,位于package pub.qingyun.web;包下:
package pub.qingyun.web;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@RestController
@CrossOrigin
@Slf4j
public class ImageController {
// 圖片根目錄
private static final Path IMAGE_ROOT = Paths.get("F:", "Temp").toAbsolutePath().normalize();
/**
* 獲取圖片資源并返回給客戶端
*
* @param imagePath 圖片文件的相對路徑參數(shù)
* @return ResponseEntity<UrlResource> 包含圖片資源的響應(yīng)實體,包含適當?shù)腍TTP狀態(tài)碼和響應(yīng)頭
*/
@GetMapping("/showImage")
public ResponseEntity<UrlResource> getImage(@RequestParam String imagePath) {
long start = System.currentTimeMillis();
// 參數(shù)校驗:檢查圖片路徑是否為空
if (imagePath == null || imagePath.trim().isEmpty()) {
log.warn("Missing imagePath parameter");
return ResponseEntity.badRequest().build();
}
// 路徑安全檢查:防止路徑遍歷攻擊
// 過濾非法字符,防止路徑穿越
if (imagePath.contains("..") || imagePath.contains("\\") || imagePath.startsWith("/")) {
log.warn("Forbidden path access attempt: [PATH_REDACTED]");
return ResponseEntity.status(403).build();
}
Path resolvedPath = IMAGE_ROOT.resolve(imagePath).normalize();
if (!resolvedPath.startsWith(IMAGE_ROOT)) {
log.warn("Forbidden path access attempt: [PATH_REDACTED]");
return ResponseEntity.status(403).build();
}
// 文件存在性檢查:驗證文件是否存在且為常規(guī)文件
if (!Files.exists(resolvedPath) || !Files.isRegularFile(resolvedPath)) {
log.info("Image not found: [PATH_REDACTED]");
return ResponseEntity.notFound().build();
}
// 緩存文件長度,避免重復(fù)調(diào)用
long fileLength = resolvedPath.toFile().length();
// 創(chuàng)建資源對象
UrlResource resource;
try {
resource = new UrlResource(resolvedPath.toUri());
} catch (MalformedURLException e) {
log.error("Failed to create resource for: [PATH_REDACTED], Malformed URL", e);
return ResponseEntity.status(500).build();
} catch (Exception e) {
log.error("Failed to create resource for: [PATH_REDACTED]", e);
return ResponseEntity.status(500).build();
}
// 設(shè)置響應(yīng)頭信息
HttpHeaders headers = new HttpHeaders();
headers.setCacheControl("public, max-age=86400"); // 緩存 1 天
headers.setExpires(System.currentTimeMillis() + 86400_000L); // 過期時間
headers.setContentDispositionFormData("inline", resource.getFilename());
log.info("getImage [PATH_REDACTED] ({} bytes) cost: {}ms", fileLength, (System.currentTimeMillis() - start));
// 構(gòu)建并返回成功響應(yīng)
return ResponseEntity.ok()
.headers(headers)
.contentType(MediaType.IMAGE_JPEG)
.contentLength(fileLength)
.body(resource);
}
}這個代碼段展示了一個簡單的Spring Boot REST控制器,用于從指定路徑加載圖片并將其作為資源返回給客戶端。它包括必要的安全措施來防止?jié)撛诘穆窂奖闅v攻擊,并設(shè)置了緩存控制頭以提高性能。希望這段代碼能為您提供構(gòu)建自己的圖片服務(wù)的幫助!
到此這篇關(guān)于Spring Boot應(yīng)用實現(xiàn)圖片資源服務(wù)的文章就介紹到這了,更多相關(guān)Spring Boot圖片資源服務(wù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
基于Spring Boot DevTools實現(xiàn)開發(fā)過程優(yōu)化
這篇文章主要介紹了基于Spring Boot DevTools實現(xiàn)開發(fā)過程優(yōu)化,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-09-09
Java多線程事務(wù)回滾@Transactional失效處理方案
這篇文章主要介紹了Java多線程事務(wù)回滾@Transactional失效處理方案,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的朋友可以參考一下2022-08-08
Spring BeanPostProcessor(后置處理器)的用法
這篇文章主要介紹了Spring BeanPostProcessor(后置處理器)的用法,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-10-10
java.lang.Instrument 代理Agent使用詳細介紹
這篇文章主要介紹了java.lang.Instrument 代理Agent使用詳細介紹的相關(guān)資料,附有實例代碼,幫助大家學(xué)習(xí)參考,需要的朋友可以參考下2016-11-11

