feige
2025-06-20 46913f8e05b8b6968f651a0d8cd4b94f726e47e2
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
package com.ruoyi.service.impl;
 
import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.transfer.TransferManager;
import com.qcloud.cos.transfer.TransferManagerConfiguration;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
 
import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
 
@Service
@ConfigurationProperties(prefix = "tencent.cos")
public class GetOrPut {
    // 从配置文件读取的参数
    private String secretId;
    private String secretKey;
    private String bucketName;
    private String region;
    private String baseUrl;
 
    private COSClient cosClient;
    private TransferManager transferManager;
 
    // 初始化配置
    @PostConstruct
    private void init() {
        // 1. 初始化用户身份信息
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
 
        // 2. 设置bucket的区域
        Region region = new Region(this.region);
        ClientConfig clientConfig = new ClientConfig(region);
        clientConfig.setHttpProtocol(HttpProtocol.https);
 
        // 3. 生成cos客户端
        cosClient = new COSClient(cred, clientConfig);
 
        // 4. 初始化传输管理器(用于大文件上传)
        ExecutorService threadPool = Executors.newFixedThreadPool(32);
        TransferManagerConfiguration transferConfig = new TransferManagerConfiguration();
        transferConfig.setMultipartUploadThreshold(5 * 1024 * 1024);
        transferManager = new TransferManager(cosClient, threadPool);
        transferManager.setConfiguration(transferConfig);
    }
 
    /**
     * 上传文件(MultipartFile方式)
     * @param file 上传的文件
     * @return 文件访问URL
     */
    public String uploadFile(MultipartFile file) {
        try {
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExt = originalFilename.substring(originalFilename.lastIndexOf("."));
            String key = java.util.UUID.randomUUID().toString() + fileExt;
 
 
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentLength(file.getSize());
            metadata.setContentType(file.getContentType());
 
            PutObjectRequest putObjectRequest = new PutObjectRequest(
                    bucketName,
                    key,
                    file.getInputStream(),
                    metadata
            );
 
            // 上传文件
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            return baseUrl + "/" + key;
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败", e);
        }
    }
 
    /**
     * 上传本地文件
     * @param localFilePath 本地文件路径
     * @return 文件访问URL
     */
    public String uploadLocalFile(String localFilePath) {
        File localFile = new File(localFilePath);
        String key = UUID.randomUUID().toString() + getFileExtension(localFile.getName());
 
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
        cosClient.putObject(putObjectRequest);
        return  key;
    }
 
    /**
     * 上传本地文件
     * @param fileUrl 本地文件路径
     * @return 文件访问URL
     */
    public String uploadWebFile(String fileUrl) throws IOException {
        // 假设 fileUrl 是你要上传的文件 URL
        System.out.println(fileUrl);
        URL url = new URL(fileUrl);
        InputStream inputStream = url.openStream();
 
        URLConnection connection = url.openConnection();
 
        // 获取文件的大小(字节数)
        int contentLength = connection.getContentLength();
        // 获取文件类型
        String type = connection.getContentType();
// 获取文件的扩展名(如果需要)
        String fileExtension = fileUrl.substring(fileUrl.lastIndexOf("."));
        String key = UUID.randomUUID().toString() + fileExtension;
 
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(contentLength);
        metadata.setContentType(type);
// 创建 PutObjectRequest 请求对象,直接传入 InputStream
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream, metadata);
 
// 上传文件
        cosClient.putObject(putObjectRequest);
 
// 关闭输入流
        inputStream.close();
 
        return  key;
    }
 
    /**
     * 下载文件到本地
     * @param key 文件唯一标识
     * @param localFilePath 本地存储路径
     */
    public void downloadFile(String key, String localFilePath) {
        File downFile = new File(localFilePath);
        GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
        cosClient.getObject(getObjectRequest, downFile);
    }
 
    /**
     * 获取文件输入流
     * @param key 文件唯一标识
     * @return 文件输入流
     */
    public InputStream getFileStream(String key) {
        COSObject cosObject = cosClient.getObject(bucketName, key);
        return cosObject.getObjectContent();
    }
 
    /**
     * 删除文件
     * @param key 文件唯一标识
     */
    public void deleteFile(String key) {
        cosClient.deleteObject(bucketName, key);
    }
 
    // 获取文件扩展名
    private String getFileExtension(String fileName) {
        return fileName.substring(fileName.lastIndexOf("."));
    }
 
    // Getter/Setter 用于配置注入
    public void setSecretId(String secretId) { this.secretId = secretId; }
    public void setSecretKey(String secretKey) { this.secretKey = secretKey; }
    public void setBucketName(String bucketName) { this.bucketName = bucketName; }
    public void setRegion(String region) { this.region = region; }
    public void setBaseUrl(String baseUrl) { this.baseUrl = baseUrl; }
}