add file
Change-Id: I49ce6d06ec46cbe679e4b8771031461047c704bb
diff --git a/src/main/java/com/g9/g9backend/controller/FileController.java b/src/main/java/com/g9/g9backend/controller/FileController.java
index 1f9ccd2..7b4e339 100644
--- a/src/main/java/com/g9/g9backend/controller/FileController.java
+++ b/src/main/java/com/g9/g9backend/controller/FileController.java
@@ -1,18 +1,86 @@
package com.g9.g9backend.controller;
+import com.g9.g9backend.pojo.TorrentRecord;
+import com.g9.g9backend.service.TorrentRecordService;
+import lombok.Getter;
+import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import org.springframework.http.ResponseEntity;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.multipart.MultipartFile;
+
+import java.io.File;
+import java.io.IOException;
/**
* FileController 文件控制器类,处理与文件相关的请求
*
* @author Seamher
*/
+@Getter
+@Setter
@RestController
@RequestMapping("/file")
public class FileController {
+ private TorrentRecordService torrentRecordService;
+
private final Logger logger = LoggerFactory.getLogger(FileController.class);
+
+ public FileController(TorrentRecordService torrentRecordService) {
+ this.torrentRecordService = torrentRecordService;
+ }
+
+ @PostMapping
+ public ResponseEntity<String> uploadFile(@RequestBody MultipartFile file) {
+ // 相对路径(可在资源根路径创建 upload 文件夹)
+ String UPLOAD_DIR = "upload";
+
+ // 获取原始文件名
+ String originalFilename = file.getOriginalFilename();
+ if (originalFilename.isEmpty()) {
+ return ResponseEntity.badRequest().body("文件名为空");
+ }
+
+ // 为文件名加时间戳,防止重名冲突
+ String filename = System.currentTimeMillis() + "_" + originalFilename;
+
+ // 构建文件保存目录(确保 upload 目录存在)
+ File uploadDir = new File(UPLOAD_DIR);
+ if (!uploadDir.exists()) {
+ boolean created = uploadDir.mkdirs(); // 创建目录
+ if (!created) {
+ logger.error("无法创建上传目录: " + uploadDir.getAbsolutePath());
+ return ResponseEntity.internalServerError().body("无法创建上传目录");
+ }
+ }
+
+ // 构建完整的文件路径
+ File dest = new File(uploadDir, filename);
+
+ try {
+ // 保存文件
+ file.transferTo(dest);
+ } catch (IOException e) {
+ logger.error("上传失败: " + e.getMessage(), e);
+ return ResponseEntity.internalServerError().body("上传失败");
+ }
+
+ // 返回访问 URL(你可能需要根据 Nginx 的静态资源映射来配置)
+ String url = "http://localhost:65/" + filename;
+
+ return ResponseEntity.ok(url);
+ }
+
+ @PostMapping(value = "bt")
+ public ResponseEntity<String> uploadBTFile(@RequestBody TorrentRecord torrentRecord) {
+ torrentRecordService.save(torrentRecord);
+
+ return ResponseEntity.ok("");
+ }
+
}