package com.rongyichuang.common.api;
|
|
import com.rongyichuang.judge.service.CosService;
|
import org.springframework.http.ResponseEntity;
|
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.multipart.MultipartFile;
|
import org.springframework.beans.factory.annotation.Autowired;
|
|
import java.util.HashMap;
|
import java.util.Map;
|
import java.util.UUID;
|
|
@RestController
|
@RequestMapping("/upload")
|
@CrossOrigin(origins = {"http://localhost:3000", "http://localhost:3001"})
|
public class FileUploadController {
|
|
@Autowired
|
private CosService cosService;
|
|
@PostMapping("/image")
|
public ResponseEntity<Map<String, Object>> uploadImage(@RequestParam("file") MultipartFile file) {
|
try {
|
// 生成唯一文件名
|
String originalFilename = file.getOriginalFilename();
|
String fileExtension = "";
|
if (originalFilename != null && originalFilename.contains(".")) {
|
fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
|
}
|
String uniqueFileName = UUID.randomUUID().toString() + fileExtension;
|
|
// 直接上传文件到COS
|
String relativePath = cosService.uploadFile(file, uniqueFileName);
|
|
// 构建文件访问URL
|
String fileUrl = cosService.getFileUrl(relativePath);
|
|
Map<String, Object> response = new HashMap<>();
|
response.put("success", true);
|
response.put("url", fileUrl);
|
response.put("fileName", originalFilename); // 保持原始文件名(带后缀)
|
response.put("fileSize", file.getSize());
|
response.put("path", relativePath); // 只返回相对路径
|
|
return ResponseEntity.ok(response);
|
} catch (Exception e) {
|
Map<String, Object> response = new HashMap<>();
|
response.put("success", false);
|
response.put("error", e.getMessage());
|
|
return ResponseEntity.badRequest().body(response);
|
}
|
}
|
}
|