| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- package space.anyi.petServiceManagementSystem.server.service.impl;
- import org.springframework.stereotype.Service;
- import org.springframework.web.multipart.MultipartFile;
- import space.anyi.petServiceManagementSystem.server.common.BusinessException;
- import space.anyi.petServiceManagementSystem.server.service.ImageService;
- import java.io.IOException;
- import java.nio.file.Files;
- import java.nio.file.Path;
- import java.nio.file.Paths;
- import java.time.LocalDate;
- import java.util.List;
- import java.util.UUID;
- @Service
- public class ImageServiceImpl implements ImageService {
- private static final List<String> ALLOWED_EXTENSIONS = List.of("jpg", "jpeg", "png", "gif", "webp", "bmp");
- private static final String UPLOAD_DIR = "./upload/";
- @Override
- public String upload(MultipartFile file) {
- if (file == null || file.isEmpty()) {
- throw new BusinessException("上传文件不能为空");
- }
- String originalFilename = file.getOriginalFilename();
- if (originalFilename == null || !originalFilename.contains(".")) {
- throw new BusinessException("文件缺少扩展名");
- }
- String ext = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
- if (!ALLOWED_EXTENSIONS.contains(ext)) {
- throw new BusinessException("不支持的图片格式,仅允许: " + String.join(", ", ALLOWED_EXTENSIONS));
- }
- String filename = LocalDate.now() + "_" + UUID.randomUUID() + "." + ext;
- Path uploadPath = Paths.get(UPLOAD_DIR);
- try {
- Files.createDirectories(uploadPath);
- Files.write(uploadPath.resolve(filename), file.getBytes());
- } catch (IOException e) {
- throw new BusinessException("文件上传失败: " + e.getMessage());
- }
- return filename;
- }
- }
|