diff --git a/src/main/java/org/cmh/backend/CourseManagement/controller/FileController.java b/src/main/java/org/cmh/backend/CourseManagement/controller/FileController.java index 99d9350..7c488b0 100644 --- a/src/main/java/org/cmh/backend/CourseManagement/controller/FileController.java +++ b/src/main/java/org/cmh/backend/CourseManagement/controller/FileController.java @@ -1,20 +1,49 @@ package org.cmh.backend.CourseManagement.controller; +import org.cmh.backend.CourseManagement.dto.UploadFileResponse; import org.springframework.core.io.UrlResource; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; -import org.springframework.web.bind.annotation.GetMapping; -import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.*; import org.springframework.core.io.Resource; +import org.springframework.web.multipart.MultipartFile; +import java.io.IOException; +import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +@RestController +@RequestMapping("/courses") public class FileController { private static final String UPLOAD_DIR = "uploads/"; + @PostMapping("/upload") + public ResponseEntity uploadFile(@RequestParam("file") MultipartFile file) { + if (file.isEmpty()) { + return new ResponseEntity<>(new UploadFileResponse("文件不能为空", null), HttpStatus.BAD_REQUEST); + } + + try { + // 确保上传目录存在 + Path uploadDirPath = Paths.get(UPLOAD_DIR); + if (!Files.exists(uploadDirPath)) { + Files.createDirectories(uploadDirPath); + } + + // 生成文件路径 + byte[] bytes = file.getBytes(); + Path path = Paths.get(UPLOAD_DIR + file.getOriginalFilename()); + Files.write(path, bytes); + + // 返回成功信息 + return new ResponseEntity<>(new UploadFileResponse("文件上传成功", "/api/courses/files/" + file.getOriginalFilename()), HttpStatus.OK); + } catch (IOException e) { + return new ResponseEntity<>(new UploadFileResponse("文件上传失败", null), HttpStatus.INTERNAL_SERVER_ERROR); + } + } @GetMapping("/files/{filename}") public ResponseEntity getFile(@PathVariable String filename) { try {