上傳圖片時需驗證尺寸是否符合規範(如頭像限制 200x200),防止前端繞過檢查或圖片變形模糊。
@PostMapping(value = "/uploadImg", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public String upload(@RequestParam("file") MultipartFile file) {
// 1. MIME 類型初步過濾
String contentType = file.getContentType(); // image/jpeg, image/png...
if (contentType == null || !contentType.startsWith("image/")) {
return "非圖片格式";
}
// 2. 讀取圖片元資料獲取寬高
try (InputStream is = file.getInputStream()) {
BufferedImage image = ImageIO.read(is);
if (image == null) {
return "無法解析圖片,可能被偽裝";
}
int width = image.getWidth();
int height = image.getHeight();
System.out.println("寬: " + width + "px, 高: " + height + "px");
// 3. 業務驗證
if (width > 2000 || height > 2000) {
return "圖片尺寸超過限制";
}
// 繼續儲存邏輯...
} catch (IOException e) {
return "讀取失敗: " + e.getMessage();
}
return "success";
}
ImageIO.read(InputStream) 解碼圖片頭部即可獲取尺寸,不會載入完整像素資料,效能良好。BufferedImage == null 表示流無法識別為圖片格式,可作為防偽裝檢查(如 .doc 改名 .png)。getWidth()/getHeight() 回傳 int。JDK 內建支援 JPEG、PNG、BMP、WBMP、GIF。若需 WebP、HEIC 等現代格式,需引入 TwelveMonkeys ImageIO 擴展包。
@Valid + 自定義註解 @ImageDimension(maxWidth=2000, maxHeight=2000) 實現聲明式驗證。metadata-extractor 庫讀取 EXIF 方向標籤,自動旋轉修正。