admin
2024-07-25 47e3087067abd35e6337c011f96d2338c0bb1aae
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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
package org.yeshi.utils.tencentcloud;
 
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
 
import org.apache.commons.codec.digest.HmacUtils;
import org.apache.commons.lang.ArrayUtils;
import org.yeshi.utils.FileUtil;
import org.yeshi.utils.StringUtil;
import org.yeshi.utils.entity.FileUploadResult;
import org.yeshi.utils.tencentcloud.entity.COSInitParams;
 
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.model.COSObjectSummary;
import com.qcloud.cos.model.ListObjectsRequest;
import com.qcloud.cos.model.ObjectListing;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.region.Region;
 
public class COSManager {
    static long appId = 0L;
    static String secretId = "";
    static String secretKey = "";
    // 设置要操作的bucket
    static String bucketName = "";
    static COSClient cosClient;
    static String totalBucketName = "";
    static String accessHost = "";
 
    static COSManager instance;
 
    public static COSManager getInstance() {
        if (instance == null)
            instance = new COSManager();
        return instance;
    }
 
    /**
     * 初始化,在使用之前必须调用此方法
     *
     * @param params
     */
    public void init(COSInitParams params) {
        appId = params.getAppId();
        secretId = params.getSecretId();
        secretKey = params.getSecretKey();
        bucketName = params.getBucketName();
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        ClientConfig clientConfig = new ClientConfig(new Region(params.getRegion()));
        cosClient = new COSClient(cred, clientConfig);
        // bucket的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
        totalBucketName = bucketName + "-" + appId;
        accessHost = params.getAccessHost();
    }
 
    public FileUploadResult uploadFile(File f, String key) {
        if (key != null && !key.startsWith("/"))
            key = "/" + key;
        PutObjectRequest putObjectRequest = new PutObjectRequest(totalBucketName, key, f);
 
        try {
            PutObjectResult result = cosClient.putObject(putObjectRequest);
 
            if (StringUtil.isNullOrEmpty(accessHost)) {
                return new FileUploadResult(String.format("http://%s.file.myqcloud.com%s", totalBucketName, key),
                        result.getETag());
            } else {
                return new FileUploadResult(String.format("%s%s", accessHost, key),
                        result.getETag());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
    public FileUploadResult uploadInputStream(InputStream inputStream, String key) {
        int count = 0;
        try {
            count = inputStream.available();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
 
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(count);
 
        if (key != null && !key.startsWith("/"))
            key = "/" + key;
        PutObjectRequest putObjectRequest = new PutObjectRequest(totalBucketName, key, inputStream, metadata);
        try {
            PutObjectResult result = cosClient.putObject(putObjectRequest);
 
            return new FileUploadResult(String.format("http://%s.file.myqcloud.com%s", totalBucketName, key),
                    result.getETag());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
 
    public FileUploadResult uploadFile(InputStream inputStream, String key) {
        if (key != null && !key.startsWith("/"))
            key = "/" + key;
        String dir = FileUtil.getCacheDir();
        String tempPath = dir + "/temp_" + System.currentTimeMillis() + "_" + (long) (Math.random() * 100000000);
        try {
 
            try {
                FileUtil.saveAsFile(inputStream, tempPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (new File(tempPath).exists()) {
                return uploadFile(new File(tempPath), key);
            }
            return null;
        } finally {
            if (new File(tempPath).exists())
                new File(tempPath).delete();
        }
    }
 
    /**
     * 获取Object列表
     *
     * @param prefix-匹配字符
     * @param count-最大1000
     * @param marker-起点标记
     * @return
     */
 
    public ObjectListing getObjectList(String prefix, String marker, int count) {
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
        listObjectsRequest.setBucketName(totalBucketName);
        listObjectsRequest.setDelimiter("/");
        listObjectsRequest.setPrefix(prefix);
        listObjectsRequest.setMaxKeys(count);
        listObjectsRequest.setMarker(marker);
        ObjectListing objectListing = cosClient.listObjects(listObjectsRequest);
        return objectListing;
    }
 
    public COSObjectSummary getObjectDetail(String prefix) {
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
        listObjectsRequest.setBucketName(totalBucketName);
        listObjectsRequest.setDelimiter("/");
        listObjectsRequest.setPrefix(prefix);
        listObjectsRequest.setMaxKeys(1);
        listObjectsRequest.setMarker(null);
        ObjectListing objectListing = cosClient.listObjects(listObjectsRequest);
        if (objectListing.getObjectSummaries() != null && objectListing.getObjectSummaries().size() > 0) {
            return objectListing.getObjectSummaries().get(0);
        }
        return null;
    }
 
    // 文件是否存在
    public boolean isFileExist(String url) {
        String key = url.replace(String.format("https://%s.file.myqcloud.com", totalBucketName), "");
        try {
            cosClient.getObjectMetadata(totalBucketName, key);
            return true;
        } catch (Exception e) {
        }
        return false;
    }
 
    public boolean deleteFileByUrl(String url) {
        String key = url.replace(String.format("https://%s.file.myqcloud.com", totalBucketName), "");
        try {
            cosClient.deleteObject(totalBucketName, key);
            return true;
        } catch (Exception e) {
        }
        return false;
    }
 
    public boolean deleteFileByKey(String key) {
        try {
            cosClient.deleteObject(totalBucketName, key);
            return true;
        } catch (Exception e) {
        }
        return false;
    }
 
    public static String getUploadVideoUrl(String name) {
        if (name != null && !name.startsWith("/"))
            name = "/" + name;
        return "https://gz.file.myqcloud.com/files/v2/" + appId + "/" + bucketName + name;
    }
 
    public static String getUploadVideoFileId(String name) {
        if (name != null && !name.startsWith("/"))
            name = "/" + name;
        return "/" + appId + "/" + bucketName + name;
    }
 
    public static String getUploadVideoAuthorization() {
        long time = System.currentTimeMillis() / 1000;
        long expireTime = time + 60 * 20;// 20分钟的上传时间
        long random = (long) (1000000L * Math.random());
        String original = String.format("a=%s&b=%s&k=%s&e=%s&t=%s&r=%s&f=", appId + "", bucketName, secretId,
                (expireTime) + "", time + "", random + "");
        byte[] so = HmacUtils.hmacSha1(secretKey, original);
        byte[] or = original.getBytes();
        byte[] bts = ArrayUtils.addAll(so, or);
        String sign = StringUtil.getBase64FromByte(bts).replace("\n", "").replace("\r", "").trim();
        return sign;
    }
 
    public FileUploadResult uploadFileByte(byte[] b, String key) {
        if (key != null && !key.startsWith("/"))
            key = "/" + key;
        String dir = FileUtil.getCacheDir();
        String tempPath = dir + "/temp_" + System.currentTimeMillis() + "_" + (long) (Math.random() * 100000000);
        try {
 
            try {
                FileUtil.saveAsFileByte(b, tempPath);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (new File(tempPath).exists()) {
                return uploadFile(new File(tempPath), key);
            }
            return null;
        } finally {
            if (new File(tempPath).exists())
                new File(tempPath).delete();
        }
    }
}