ImageServiceImpl.java 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package space.anyi.petServiceManagementSystem.server.service.impl;
  2. import org.springframework.stereotype.Service;
  3. import org.springframework.web.multipart.MultipartFile;
  4. import space.anyi.petServiceManagementSystem.server.common.BusinessException;
  5. import space.anyi.petServiceManagementSystem.server.service.ImageService;
  6. import java.io.IOException;
  7. import java.nio.file.Files;
  8. import java.nio.file.Path;
  9. import java.nio.file.Paths;
  10. import java.time.LocalDate;
  11. import java.util.List;
  12. import java.util.UUID;
  13. @Service
  14. public class ImageServiceImpl implements ImageService {
  15. private static final List<String> ALLOWED_EXTENSIONS = List.of("jpg", "jpeg", "png", "gif", "webp", "bmp");
  16. private static final String UPLOAD_DIR = "./upload/";
  17. @Override
  18. public String upload(MultipartFile file) {
  19. if (file == null || file.isEmpty()) {
  20. throw new BusinessException("上传文件不能为空");
  21. }
  22. String originalFilename = file.getOriginalFilename();
  23. if (originalFilename == null || !originalFilename.contains(".")) {
  24. throw new BusinessException("文件缺少扩展名");
  25. }
  26. String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
  27. if (!ALLOWED_EXTENSIONS.contains(ext)) {
  28. throw new BusinessException("不支持的图片格式,仅允许: " + String.join(", ", ALLOWED_EXTENSIONS));
  29. }
  30. String filename = LocalDate.now() + "_" + UUID.randomUUID() + "." + ext;
  31. Path uploadPath = Paths.get(UPLOAD_DIR);
  32. try {
  33. Files.createDirectories(uploadPath);
  34. Files.write(uploadPath.resolve(filename), file.getBytes());
  35. } catch (IOException e) {
  36. throw new BusinessException("文件上传失败: " + e.getMessage());
  37. }
  38. return filename;
  39. }
  40. }