소스 검색

feat:新增图片上传和下载API

yangyi 4 달 전
부모
커밋
1df968e5d7

+ 8 - 1
src/main/java/space/anyi/petServiceManagementSystem/server/config/WebMvcConfig.java

@@ -2,6 +2,7 @@ package space.anyi.petServiceManagementSystem.server.config;
 
 import org.springframework.context.annotation.Configuration;
 import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
+import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
 import space.anyi.petServiceManagementSystem.server.interceptor.AdminInterceptor;
 import space.anyi.petServiceManagementSystem.server.interceptor.AuthInterceptor;
@@ -12,9 +13,15 @@ public class WebMvcConfig implements WebMvcConfigurer {
     public void addInterceptors(InterceptorRegistry registry) {
         registry.addInterceptor(new AuthInterceptor())
                 .addPathPatterns("/**")
-                .excludePathPatterns("/auth/**", "/swagger-ui/**", "/v3/api-docs/**");
+                .excludePathPatterns("/auth/**", "/swagger-ui/**", "/v3/api-docs/**", "/images/**");
 
         registry.addInterceptor(new AdminInterceptor())
                 .addPathPatterns("/admin/**");
     }
+
+    @Override
+    public void addResourceHandlers(ResourceHandlerRegistry registry) {
+        registry.addResourceHandler("/images/**")
+                .addResourceLocations("file:./upload/");
+    }
 }

+ 30 - 0
src/main/java/space/anyi/petServiceManagementSystem/server/controller/ImageController.java

@@ -0,0 +1,30 @@
+package space.anyi.petServiceManagementSystem.server.controller;
+
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.Parameter;
+import io.swagger.v3.oas.annotations.media.Schema;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.MediaType;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.multipart.MultipartFile;
+import space.anyi.petServiceManagementSystem.server.common.R;
+import space.anyi.petServiceManagementSystem.server.service.ImageService;
+
+@RestController
+public class ImageController {
+
+    @Autowired
+    private ImageService imageService;
+
+    private static final String URL_PREFIX = "http://localhost:8080/images/";
+
+    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
+    @Operation(summary = "上传图片")
+    public R<String> upload(@RequestBody MultipartFile imageFile) {
+        String filename = imageService.upload(imageFile);
+        return R.ok(URL_PREFIX + filename);
+    }
+}

+ 7 - 0
src/main/java/space/anyi/petServiceManagementSystem/server/service/ImageService.java

@@ -0,0 +1,7 @@
+package space.anyi.petServiceManagementSystem.server.service;
+
+import org.springframework.web.multipart.MultipartFile;
+
+public interface ImageService {
+    String upload(MultipartFile file);
+}

+ 50 - 0
src/main/java/space/anyi/petServiceManagementSystem/server/service/impl/ImageServiceImpl.java

@@ -0,0 +1,50 @@
+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;
+    }
+}

+ 4 - 0
src/main/resources/application.yaml

@@ -1,6 +1,10 @@
 spring:
   application:
     name: PetServiceManagementSystem
+  servlet:
+    multipart:
+      max-file-size: 10MB
+      max-request-size: 10MB
   datasource:
     url: jdbc:mysql://localhost:3306/pet_service_managemen_system?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
     username: root