longz
2026-06-04 da780b14b8db78043d2c0f27d3bfd73111e6d550
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
package com.stylefeng.guns.modular.system.util;
 
import com.qcloud.cos.COSClient;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
 
import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
 
@Service
public class COSUploadService {
    
    @Resource
    private COSClient cosClient;
    
    @Value("${cos.bucketName}")
    private String bucketName;
    
    @Value("${cos.baseUrl}")
    private  String baseUrl="https://cb-1358396420.cos.ap-shanghai.mvacloud.com";
    
    /**
     * 上传MultipartFile到COS
     * @param file MultipartFile文件
     * @return 文件访问URL
     */
    public  String uploadFile(MultipartFile file) {
        // 参数校验
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }
        
        String originalFilename = file.getOriginalFilename();
        String fileExtension = getFileExtension(originalFilename);
        String fileName = generateFileName(fileExtension);
        String key = fileName;
 
        try (InputStream inputStream = file.getInputStream()) {
            // 创建上传请求
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                bucketName, 
                key,
                inputStream,
                null
            );
 
            // 执行上传
            PutObjectResult result = cosClient.putObject(putObjectRequest);
            
            // 返回文件访问URL
            return baseUrl + "/" + key;
            
        } catch (IOException e) {
            throw new RuntimeException("文件读取失败:" + e.getMessage(), e);
        } catch (CosServiceException e) {
            throw new RuntimeException("COS服务异常:" + e.getErrorMessage(), e);
        } catch (CosClientException e) {
            throw new RuntimeException("COS客户端异常:" + e.getMessage(), e);
        }
    }
    
    /**
     * 上传MultipartFile到COS(带自定义文件名)
     */
    public String uploadFile(MultipartFile file, String directory, String customFileName) {
        if (file == null || file.isEmpty()) {
            throw new IllegalArgumentException("文件不能为空");
        }
        
        String fileExtension = getFileExtension(file.getOriginalFilename());
        String fileName = customFileName + fileExtension;
        String key = directory + fileName;
        
        try (InputStream inputStream = file.getInputStream()) {
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                bucketName, 
                key, 
                inputStream, 
                null
            );
            
            cosClient.putObject(putObjectRequest);
            
            return baseUrl + "/" + key;
            
        } catch (IOException e) {
            throw new RuntimeException("文件读取失败:" + e.getMessage(), e);
        }
    }
    
    /**
     * 上传图片并压缩(示例:可以结合其他工具实现)
     */
    public String uploadImage(MultipartFile file, boolean compress) {
        // 校验图片格式
        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image/")) {
            throw new IllegalArgumentException("只能上传图片文件");
        }
        
        return uploadFile(file);
    }
    
    /**
     * 生成唯一文件名
     */
    private  String generateFileName(String fileExtension) {
        return UUID.randomUUID().toString().replace("-", "") + fileExtension;
    }
    
    /**
     * 获取文件扩展名
     */
    private  String getFileExtension(String filename) {
        if (filename == null || filename.lastIndexOf(".") == -1) {
            return "";
        }
        return filename.substring(filename.lastIndexOf("."));
    }
    
    /**
     * 批量上传文件
     */
    public List<String> uploadFiles(MultipartFile[] files, String directory) {
        List<String> urls = new ArrayList<>();
        for (MultipartFile file : files) {
            try {
                String url = uploadFile(file);
                urls.add(url);
            } catch (Exception e) {
                // 记录失败的文件,继续上传其他文件
                e.printStackTrace();
            }
        }
        return urls;
    }
}