|
28 | 28 | import java.io.ByteArrayInputStream; |
29 | 29 | import java.io.ByteArrayOutputStream; |
30 | 30 | import java.io.IOException; |
| 31 | +import java.nio.charset.StandardCharsets; |
31 | 32 | import java.util.Base64; |
32 | 33 | import java.util.HashMap; |
33 | 34 | import java.util.Map; |
@@ -238,25 +239,66 @@ public static String extractContentType(String base64Data) { |
238 | 239 | } |
239 | 240 |
|
240 | 241 | /** |
241 | | - * 检查文件是否为图片类型 |
| 242 | + * 图片验证 |
242 | 243 | */ |
243 | 244 | public static boolean validateByImageIO(MultipartFile file) { |
244 | 245 | try { |
| 246 | + String filename = file.getOriginalFilename(); |
| 247 | + if (filename == null) { |
| 248 | + return false; |
| 249 | + } |
| 250 | + // 获取文件扩展名 |
| 251 | + String extension = getFileExtension(filename).toLowerCase(); |
| 252 | + |
| 253 | + if ("svg".equals(extension)) { |
| 254 | + return isSvgFile(file); |
| 255 | + } |
| 256 | + |
245 | 257 | BufferedImage image = ImageIO.read(new ByteArrayInputStream(file.getBytes())); |
246 | | - return image != null; // 如果是图片,返回true |
| 258 | + return image != null; |
247 | 259 | } catch (IOException e) { |
248 | 260 | return false; |
249 | 261 | } |
250 | 262 | } |
251 | 263 |
|
252 | 264 | /** |
253 | | - * 将MultipartFile转换为Base64字符串 |
| 265 | + * SVG文件验证 |
| 266 | + */ |
| 267 | + private static boolean isSvgFile(MultipartFile file) { |
| 268 | + try { |
| 269 | + byte[] bytes = file.getBytes(); |
| 270 | + String content = new String(bytes, StandardCharsets.UTF_8); |
| 271 | + |
| 272 | + // 简单检查:包含<svg标签和SVG命名空间 |
| 273 | + return content.contains("<svg") && |
| 274 | + (content.contains("xmlns=\"http://www.w3.org/2000/svg\"") || |
| 275 | + content.contains("xmlns='http://www.w3.org/2000/svg'")); |
| 276 | + |
| 277 | + } catch (IOException e) { |
| 278 | + return false; |
| 279 | + } |
| 280 | + } |
| 281 | + /** |
| 282 | + * 获取文件扩展名 |
| 283 | + */ |
| 284 | + private static String getFileExtension(String filename) { |
| 285 | + if (filename == null || !filename.contains(".")) { |
| 286 | + return ""; |
| 287 | + } |
| 288 | + return filename.substring(filename.lastIndexOf(".") + 1); |
| 289 | + } |
| 290 | + /** |
| 291 | + * 简化版Base64转换 |
254 | 292 | */ |
255 | 293 | public static String convertToBase64(MultipartFile file) throws IOException { |
256 | 294 | String mimeType = file.getContentType(); |
257 | 295 | byte[] fileBytes = file.getBytes(); |
258 | 296 | String base64 = Base64.getEncoder().encodeToString(fileBytes); |
259 | | - |
| 297 | + // 如果是SVG文件,修正MIME类型 |
| 298 | + String filename = file.getOriginalFilename(); |
| 299 | + if (filename != null && filename.toLowerCase().endsWith(".svg")) { |
| 300 | + mimeType = "image/svg+xml"; |
| 301 | + } |
260 | 302 | return "data:" + mimeType + ";base64," + base64; |
261 | 303 | } |
262 | 304 |
|
|
0 commit comments