Просмотр исходного кода

feat: 增加文件上传功能,全局异常处理机制

ChenSiTong 6 лет назад
Родитель
Сommit
30ecce785c

+ 26 - 0
src/main/java/nju/seec/helper/config/FileProperties.java

@@ -0,0 +1,26 @@
+package nju.seec.helper.config;
+
+import lombok.Data;
+import org.springframework.boot.context.properties.ConfigurationProperties;
+import org.springframework.stereotype.Component;
+import org.springframework.util.ResourceUtils;
+
+import java.io.FileNotFoundException;
+import java.nio.file.Path;
+
+/**
+ * @author cst
+ */
+@ConfigurationProperties(prefix = "file")
+@Component
+@Data
+public class FileProperties {
+    private String storeDir;
+
+    public Path getFileDirPath() throws FileNotFoundException {
+        Path classpath = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX).toPath();
+        Path staticPath = classpath.resolve("static/");
+
+        return staticPath.resolve(storeDir);
+    }
+}

+ 16 - 0
src/main/java/nju/seec/helper/logic/service/FileService.java

@@ -0,0 +1,16 @@
+package nju.seec.helper.logic.service;
+
+import org.springframework.web.multipart.MultipartFile;
+
+/**
+ * @author cst
+ */
+public interface FileService {
+    /**
+     * 存储文件
+     *
+     * @param file 上传文件
+     * @return 文件路径
+     */
+    String upload(MultipartFile file);
+}

+ 44 - 0
src/main/java/nju/seec/helper/logic/service/impl/FileServiceImpl.java

@@ -0,0 +1,44 @@
+package nju.seec.helper.logic.service.impl;
+
+import lombok.SneakyThrows;
+import nju.seec.helper.config.FileProperties;
+import nju.seec.helper.logic.service.FileService;
+import org.springframework.stereotype.Service;
+import org.springframework.util.StringUtils;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.File;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Objects;
+import java.util.UUID;
+
+/**
+ * @author cst
+ */
+@Service
+public class FileServiceImpl implements FileService {
+    private final FileProperties fileProperties;
+
+    @SneakyThrows
+    public FileServiceImpl(FileProperties fileProperties) {
+        this.fileProperties = fileProperties;
+
+        Path fileDir = fileProperties.getFileDirPath();
+        if (Files.notExists(fileDir)) {
+            Files.createDirectories(fileDir);
+        }
+    }
+
+    @SneakyThrows
+    @Override
+    public String upload(MultipartFile file) {
+        String filename = StringUtils.cleanPath(Objects.requireNonNull(file.getOriginalFilename()));
+        String fileExtension = filename.substring(filename.lastIndexOf('.'));
+        filename = UUID.randomUUID() + fileExtension;
+        Path filepath = fileProperties.getFileDirPath().resolve(filename);
+        file.transferTo(filepath);
+
+        return File.separator + fileProperties.getStoreDir() + filename;
+    }
+}

+ 25 - 0
src/main/java/nju/seec/helper/util/exception/HelperException.java

@@ -0,0 +1,25 @@
+package nju.seec.helper.util.exception;
+
+import lombok.AllArgsConstructor;
+import lombok.Getter;
+
+/**
+ * @author cst
+ */
+@Getter
+@AllArgsConstructor(staticName = "of")
+public class HelperException extends RuntimeException {
+    private ExceptionType type;
+    private String msg;
+
+    @Getter
+    public enum ExceptionType {
+        FORBIDDEN(403), NOT_FOUND(404), SYSTEM_ERROR(500);
+
+        private int code;
+
+        ExceptionType(int code) {
+            this.code = code;
+        }
+    }
+}

+ 23 - 0
src/main/java/nju/seec/helper/web/HelperExceptionHandler.java

@@ -0,0 +1,23 @@
+package nju.seec.helper.web;
+
+import nju.seec.helper.util.exception.HelperException;
+import nju.seec.helper.web.response.ErrorResponse;
+import org.springframework.web.bind.MethodArgumentNotValidException;
+import org.springframework.web.bind.annotation.ExceptionHandler;
+import org.springframework.web.bind.annotation.RestControllerAdvice;
+
+/**
+ * @author cst
+ */
+@RestControllerAdvice
+public class HelperExceptionHandler {
+    @ExceptionHandler(MethodArgumentNotValidException.class)
+    public ErrorResponse handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
+        return ErrorResponse.of(400, ex.getLocalizedMessage());
+    }
+
+    @ExceptionHandler(HelperException.class)
+    public ErrorResponse handleHelperException(HelperException ex) {
+        return ErrorResponse.of(ex.getType().getCode(), ex.getMsg());
+    }
+}

+ 26 - 0
src/main/java/nju/seec/helper/web/controller/FileController.java

@@ -0,0 +1,26 @@
+package nju.seec.helper.web.controller;
+
+import nju.seec.helper.logic.service.FileService;
+import nju.seec.helper.web.response.ResourceResponse;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.multipart.MultipartFile;
+
+/**
+ * @author cst
+ */
+@RestController
+@RequestMapping("/api/file")
+public class FileController {
+    private final FileService fileService;
+
+    public FileController(FileService fileService) {
+        this.fileService = fileService;
+    }
+
+    @PostMapping("/upload")
+    public ResourceResponse<String> upload(MultipartFile file) {
+        return ResourceResponse.of(fileService.upload(file));
+    }
+}