完成了文件上传的Controller

This commit is contained in:
Chester.X 2024-07-04 22:47:52 +08:00
parent ef10067345
commit 9569a30a8a

View File

@ -1,20 +1,49 @@
package org.cmh.backend.CourseManagement.controller; package org.cmh.backend.CourseManagement.controller;
import org.cmh.backend.CourseManagement.dto.UploadFileResponse;
import org.springframework.core.io.UrlResource; import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders; import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus; import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.core.io.Resource; 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.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
@RestController
@RequestMapping("/courses")
public class FileController { public class FileController {
private static final String UPLOAD_DIR = "uploads/"; private static final String UPLOAD_DIR = "uploads/";
@PostMapping("/upload")
public ResponseEntity<UploadFileResponse> 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}") @GetMapping("/files/{filename}")
public ResponseEntity<Resource> getFile(@PathVariable String filename) { public ResponseEntity<Resource> getFile(@PathVariable String filename) {
try { try {