chenjiahe
2022-07-27 386c2a4bfe398298db827607a32c1aa81cf7d554
提交 | 用户 | age
7b319c 1 package com.hx.util;
C 2
cd5e48 3 import com.hx.exception.TipsException;
7b319c 4 import com.qcloud.cos.COSClient;
C 5 import com.qcloud.cos.ClientConfig;
6 import com.qcloud.cos.auth.BasicCOSCredentials;
7 import com.qcloud.cos.auth.COSCredentials;
cd5e48 8 import com.qcloud.cos.exception.CosClientException;
C 9 import com.qcloud.cos.exception.CosServiceException;
10 import com.qcloud.cos.http.HttpProtocol;
11 import com.qcloud.cos.model.GetObjectRequest;
ccd95b 12 import com.qcloud.cos.model.ObjectMetadata;
7b319c 13 import com.qcloud.cos.model.PutObjectRequest;
C 14 import com.qcloud.cos.model.PutObjectResult;
15 import com.qcloud.cos.region.Region;
cd5e48 16 import com.qcloud.cos.transfer.Download;
C 17 import com.qcloud.cos.transfer.TransferManager;
7b319c 18 import org.springframework.web.multipart.MultipartFile;
C 19
20 import java.io.File;
21 import java.io.IOException;
cd5e48 22 import java.util.concurrent.ExecutorService;
C 23 import java.util.concurrent.Executors;
7b319c 24
C 25 /**腾讯云 COS
26  * @author ChenJiaHe
27  * @date 2020-12-03
28  */
29 public class COSUtil {
30
31     /** 后端调用上传图片
32      * @param key 上传路径(包括图片名称和和后缀),指定要上传到 COS 上对象键
33      * @param localFile
34      * @param secretId 用户id
35      * @param secretKey 用户秘钥
36      * @param regionName 存在域,参考腾讯云
37      * @param bucketName 指定要上传到的存储桶
38      * @return
39      * @throws IOException
40      */
ccd95b 41     public static String uploadImg(String key,MultipartFile localFile,String secretId, String secretKey,String regionName,String bucketName) throws IOException {
7b319c 42
C 43         // 1 初始化用户身份信息(secretId, secretKey)。
44         COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
45         // 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
46         // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
47         Region region = new Region(regionName);
48         ClientConfig clientConfig = new ClientConfig(region);
49         // 3 生成 cos 客户端。
50         COSClient cosClient = new COSClient(cred, clientConfig);
51
52         //开始上传
ccd95b 53         ObjectMetadata objectMetadata = new ObjectMetadata();
C 54         // 设置输入流长度为500
ee9728 55         objectMetadata.setContentLength(localFile.getSize());
ccd95b 56         // 设置 Content type, 默认是 application/octet-stream,对于本地文件上传,默认根据本地文件的后缀进行映射
C 57         // ,例如 jpg 文件映射 为image/jpeg对于流式上传 默认是 application/octet-stream
58         //objectMetadata.setContentType("application/pdf");
59         PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key,localFile.getInputStream(),objectMetadata);
7b319c 60         PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
C 61
62         //拼接路径
63         StringBuilder imgUrl = new StringBuilder();
486aaa 64         imgUrl.append("https://"+bucketName+".cos."+regionName+".myqcloud.com");
7b319c 65         if(key.startsWith("/")){
C 66             imgUrl.append(key);
67         }else{
68             imgUrl.append("/"+key);
69         }
a99c1c 70         cosClient.shutdown();
7b319c 71         return imgUrl.toString();
C 72
73     }
74
49f28b 75
C 76     /** 后端调用上传图片
77      * @param key 上传路径(包括图片名称和和后缀),指定要上传到 COS 上对象键
78      * @param localFile
79      * @param secretId 用户id
80      * @param secretKey 用户秘钥
81      * @param regionName 存在域,参考腾讯云
82      * @param bucketName 指定要上传到的存储桶
83      * @return
84      * @throws IOException
85      */
86     public static String uploadImg(String key,File localFile,String secretId, String secretKey,String regionName,String bucketName) throws IOException {
87
88         // 1 初始化用户身份信息(secretId, secretKey)。
89         COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
90         // 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
91         // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
92         Region region = new Region(regionName);
93         ClientConfig clientConfig = new ClientConfig(region);
94         // 3 生成 cos 客户端。
95         COSClient cosClient = new COSClient(cred, clientConfig);
96
97         // 设置 Content type, 默认是 application/octet-stream,对于本地文件上传,默认根据本地文件的后缀进行映射
98         // ,例如 jpg 文件映射 为image/jpeg对于流式上传 默认是 application/octet-stream
99         //objectMetadata.setContentType("application/pdf");
100         PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
101         PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
102
103         //拼接路径
104         StringBuilder imgUrl = new StringBuilder();
105         imgUrl.append("https://"+bucketName+".cos."+regionName+".myqcloud.com");
106         if(key.startsWith("/")){
107             imgUrl.append(key);
108         }else{
109             imgUrl.append("/"+key);
110         }
a99c1c 111         cosClient.shutdown();
49f28b 112         return imgUrl.toString();
C 113
114     }
115
cd5e48 116     /**下载文件
C 117      * @param key 上传路径(包括图片名称和和后缀),指定要上传到 COS 上对象键
118      * @param secretId 用户id
119      * @param secretKey 用户秘钥
120      * @param regionName 存在域,参考腾讯云
121      * @param bucketName 指定要上传到的存储桶
122      */
123     public static File download(String key,String secretId, String secretKey,String regionName,String bucketName){
124
125         // 使用高级接口必须先保证本进程存在一个 TransferManager 实例,如果没有则创建
126         // 详细代码参见本页:高级接口 -> 创建 TransferManager
127         TransferManager transferManager = createTransferManager( secretId, secretKey,regionName);
128         // 本地文件路径
129         File downloadFile = null;
130         try {
131             GetObjectRequest getObjectRequest;
132             //截取文件名称
133             String[] datas = key.split(regionName+".myqcloud.com/");
134             if(datas.length ==1){
135                 getObjectRequest = new GetObjectRequest(bucketName, datas[0]);
136             }else if(datas.length ==2){
137                 getObjectRequest = new GetObjectRequest(bucketName, datas[1]);
138             }else{
139                 throw new TipsException("文件路径错误【key】");
140             }
141
142             ////生成临时文件
143             //获取后缀名称
144             String suffix = key.substring(key.lastIndexOf("."));
145             downloadFile = File.createTempFile("temp", suffix);
146
147             // 返回一个异步结果 Donload, 可同步的调用 waitForCompletion 等待下载结束, 成功返回 void, 失败抛出异常
148             Download download = transferManager.download(getObjectRequest, downloadFile);
149             download.waitForCompletion();
150         } catch (CosServiceException e) {
151             e.printStackTrace();
152         } catch (CosClientException e) {
153             e.printStackTrace();
154         } catch (InterruptedException e) {
155             e.printStackTrace();
156         }catch (IOException e){
157             e.printStackTrace();
158         }finally {
159             // 确定本进程不再使用 transferManager 实例之后,关闭之
160             // 详细代码参见本页:高级接口 -> 关闭 TransferManager
161             shutdownTransferManager(transferManager);
162         }
163
164         return downloadFile;
165     }
166
167     /**
168      * 创建 TransferManager 实例,这个实例用来后续调用高级接口
169      * @param secretId
170      * @param secretKey
171      * @return
172      */
173     public static TransferManager createTransferManager(String secretId, String secretKey,String regionName) {
174         // 创建一个 COSClient 实例,这是访问 COS 服务的基础实例。
175         // 详细代码参见本页: 简单操作 -> 创建 COSClient
176         COSClient cosClient = createCOSClient( secretId, secretKey,regionName);
177
178         // 自定义线程池大小,建议在客户端与 COS 网络充足(例如使用腾讯云的 CVM,同地域上传 COS)的情况下,设置成16或32即可,可较充分的利用网络资源
179         // 对于使用公网传输且网络带宽质量不高的情况,建议减小该值,避免因网速过慢,造成请求超时。
180         ExecutorService threadPool = Executors.newFixedThreadPool(32);
181
182         // 传入一个 threadpool, 若不传入线程池,默认 TransferManager 中会生成一个单线程的线程池。
183         TransferManager transferManager = new TransferManager(cosClient, threadPool);
184
185         return transferManager;
186     }
187
188     /**
189      * 关闭管理
190      * @param transferManager
191      */
192     public static void shutdownTransferManager(TransferManager transferManager) {
193         // 指定参数为 true, 则同时会关闭 transferManager 内部的 COSClient 实例。
194         // 指定参数为 false, 则不会关闭 transferManager 内部的 COSClient 实例。
195         transferManager.shutdownNow(true);
196     }
197
198     /**
199      *  创建 COSClient 实例,这个实例用来后续调用请求
200      * @param secretId
201      * @param secretKey
202      * @return
203      */
204     public static COSClient createCOSClient(String secretId, String secretKey,String regionName) {
205         // 设置用户身份信息。
206         // SECRETID 和 SECRETKEY 请登录访问管理控制台 https://console.cloud.tencent.com/cam/capi 进行查看和管理
207         COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
208
209         // ClientConfig 中包含了后续请求 COS 的客户端设置:
210         ClientConfig clientConfig = new ClientConfig();
211
212         // 设置 bucket 的地域
213         // COS_REGION 请参照 https://cloud.tencent.com/document/product/436/6224
214         clientConfig.setRegion(new Region(regionName));
215
216         // 设置请求协议, http 或者 https
217         // 5.6.53 及更低的版本,建议设置使用 https 协议
218         // 5.6.54 及更高版本,默认使用了 https
219         clientConfig.setHttpProtocol(HttpProtocol.https);
220
221         // 以下的设置,是可选的:
222
223         // 设置 socket 读取超时,默认 30s
224         clientConfig.setSocketTimeout(300*1000);
225         // 设置建立连接超时,默认 30s
226         clientConfig.setConnectionTimeout(30*1000);
227
228         // 如果需要的话,设置 http 代理,ip 以及 port
229         //clientConfig.setHttpProxyIp("httpProxyIp");
230         //clientConfig.setHttpProxyPort(80);
231
232         // 生成 cos 客户端。
233         return new COSClient(cred, clientConfig);
234     }
235
236
7b319c 237 }