Class ContentDetector
java.lang.Object
io.leandev.appfuse.content.ContentDetector
內容類型檢測器,用於自動偵測檔案的 MIME 類型。
使用混合策略進行檢測:
- 檔案路徑檢測:優先使用 Java NIO Files.probeContentType()(基於平台實作)
- 串流檢測:使用魔術位元組分析(URLConnection.guessContentTypeFromStream)
- 副檔名降級:當以上方法失敗時,基於副檔名映射檢測常見格式
範例用法:
ContentDetector detector = new ContentDetector();
MediaType type = detector.detect(imagePath);
// type: image/jpeg
-
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionorg.springframework.http.MediaTypedetect(byte[] bytes) 檢測位元組陣列的內容類型。org.springframework.http.MediaTypedetect(InputStream input) 檢測輸入串流的內容類型。org.springframework.http.MediaType檢測檔案路徑的內容類型。
-
Constructor Details
-
ContentDetector
public ContentDetector()
-
-
Method Details
-
detect
檢測檔案路徑的內容類型。
策略:
- 使用 Files.probeContentType()(平台原生檢測)
- 降級到副檔名映射
- 最終使用預設類型
- Parameters:
path- 檔案路徑- Returns:
- MIME 類型
- Throws:
IOException- 當檔案讀取失敗時ContentException- 當參數為 null 時
-
detect
檢測輸入串流的內容類型。
使用魔術位元組分析(讀取檔案頭部特徵)。 注意:此方法會讀取串流的前幾個位元組,但會重置串流位置(如果支援 mark)。
- Parameters:
input- 輸入串流- Returns:
- MIME 類型
- Throws:
IOException- 當串流讀取失敗時ContentException- 當參數為 null 時
-
detect
檢測位元組陣列的內容類型。
內部轉換為 ByteArrayInputStream 後進行魔術位元組檢測。
- Parameters:
bytes- 位元組陣列- Returns:
- MIME 類型
- Throws:
IOException- 當讀取失敗時ContentException- 當參數為 null 時
-