peng
2025-11-06 c4938f6f4e839890b032c75c7a57333a6a9157a9
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
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);
            
            // 为兼容前端wangEditor,返回其期望的格式
            Map<String, Object> response = new HashMap<>();
            response.put("errno", 0); // 0表示成功,1表示失败
            response.put("success", true);
            Map<String, Object> data = new HashMap<>();
            data.put("url", fileUrl);
            data.put("alt", originalFilename);
            data.put("href", fileUrl);
            response.put("data", data);
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> response = new HashMap<>();
            response.put("success", false);
            response.put("errno", 1); // 0表示成功,1表示失败
            response.put("message", e.getMessage());
            
            return ResponseEntity.badRequest().body(response);
        }
    }
}