cos工具类 + 上传下载接口cos切换

This commit is contained in:
liyawei
2022-06-08 18:59:54 +08:00
parent d5497cf5bc
commit 1ff997103a
10 changed files with 501 additions and 12 deletions
@@ -241,7 +241,18 @@
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</dependency>
<!-- 腾讯 cos -->
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>5.2.4</version>
<exclusions>
<exclusion>
<artifactId>slf4j-log4j12</artifactId>
<groupId>org.slf4j</groupId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
</project>
@@ -0,0 +1,260 @@
package com.jero.common.util.oss;
import com.jero.config.oss.CosConfiguration;
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.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.http.HttpMethodName;
import com.qcloud.cos.http.HttpProtocol;
import com.qcloud.cos.region.Region;
import com.qcloud.cos.utils.IOUtils;
import lombok.extern.slf4j.Slf4j;
import org.jeecgframework.core.util.ApplicationContextUtil;
import org.jeecgframework.dict.service.AutoPoiDictServiceI;
import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.*;
import java.util.Date;
/**
* @Author: liyawei
* @Description:
* @Date: Created in 9:12 2022/6/8
*/
@Slf4j
public class CosBootUtil {
private static String secretId;
private static String secretKey;
private static String region;
private static String bucketName;
private static String appId;
private static String endPoint;
public static void setSecretId(String secretId) {
CosBootUtil.secretId = secretId;
}
public static void setSecretKey(String secretKey) {
CosBootUtil.secretKey = secretKey;
}
public static void setRegion(String region) {
CosBootUtil.region = region;
}
public static void setBucketName(String bucketName) {
CosBootUtil.bucketName = bucketName;
}
public static void setAppId(String appId) {
CosBootUtil.appId = appId;
}
public static void setEndPoint(String endPoint) {
CosBootUtil.endPoint = endPoint;
}
public static String getSecretId() {
return secretId;
}
public static String getSecretKey() {
return secretKey;
}
public static String getRegion() {
return region;
}
public static String getBucketName() {
return bucketName;
}
public static String getAppId() {
return appId;
}
public static String getEndPoint() {
return endPoint;
}
/**
* cos 工具客户端
*/
private static COSClient cosClient = null;
private static COSCredentials cred = null;
/**
* 初始化
*/
private static void init() {
CosConfiguration ccf = ApplicationContextUtil.getContext().getBean(CosConfiguration.class);
ccf.initCosBootConfiguration();
// 1 初始化用户身份信息(secretId, secretKey)
cred = new BasicCOSCredentials(secretId, secretKey);
// 2 设置bucket的区域,
ClientConfig clientConfig = new ClientConfig(new Region(region));
clientConfig.setHttpProtocol(HttpProtocol.https);
// 以下的设置,是可选的:
// 设置 socket 读取超时,默认 30s
// clientConfig.setSocketTimeout(30*1000);
// 设置建立连接超时,默认 30s
// clientConfig.setConnectionTimeout(30*1000);
// 3 生成cos客户端
cosClient = new COSClient(cred, clientConfig);
}
/**
* cos 上传
* 相同key 文件会覆盖
* @param file
* @param key
*/
public static void upload(MultipartFile file, String key){
init();
Date expirationTime = new Date(System.currentTimeMillis() + 30 * 60 * 1000);
// 生成预签名上传 URL
URL url = cosClient.generatePresignedUrl(bucketName, key, expirationTime, HttpMethodName.PUT);
log.info("生成预签名上传URL:" + url);
int responseCode = upLoadFile(url.toString(), file);
if (responseCode == 200) {
log.info("上传成功!");
} else {
log.info("上传失败!");
}
cosClient.shutdown();
}
private static int upLoadFile(String singnedurl,MultipartFile file){
InputStream inputStream= null;
DataOutputStream out = null;
int responseCode = 0;
try {
URL url= null;
url = new URL(singnedurl);
inputStream= file.getInputStream();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestMethod("PUT");
out = new DataOutputStream(connection.getOutputStream());
// 写入要上传的数据
IOUtils.copy(inputStream, out);
responseCode = connection.getResponseCode();
log.info("Service returned response code " + responseCode);
} catch (ProtocolException e) {
log.error(e.getMessage(), e);
} catch (IOException e) {
log.error(e.getMessage(), e);
} finally {
try {
inputStream.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
try {
out.close();
} catch (IOException e) {
log.error(e.getMessage(), e);
}
return responseCode;
}
}
/**
* cos 下载
* @param key
* @return
*/
public static InputStream download(String key) {
Date expirationTime = new Date(System.currentTimeMillis() + 30 * 60 * 1000);
// 生成预签名上传 URL
URL url = cosClient.generatePresignedUrl(bucketName, key, expirationTime, HttpMethodName.GET);
log.info("生成预签名上传URL:" + url);
InputStream in = downFile(url.toString());
if (in != null) {
log.info("下载成功!");
} else {
log.info("下载失败!");
}
// System.out.println("下载成功");
cosClient.shutdown();
return in;
}
private static InputStream downFile(String singnedurl) {
InputStream in = null;
try {
URL url=new URL(singnedurl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setRequestMethod("GET");
in = connection.getInputStream();
int responseCode = connection.getResponseCode();
log.info("Service returned response code " + responseCode);
// 写入要上传的数据
// IOUtils.copy(in, outputStream);
return in;
} catch (IOException e) {
e.printStackTrace();
}/* finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
// fileOutputStream.close();
}*/
return in;
}
/**
* 判断文件是否存在
* 上传,下载,删除时 必需调用此方法
* @param key
* @return
*/
public static boolean doesObjectExist(String key) {
init();
boolean objectExists = false;
try {
objectExists = cosClient.doesObjectExist(bucketName, key);
return objectExists;
} catch (CosServiceException e) {
e.printStackTrace();
} catch (CosClientException e) {
e.printStackTrace();
} finally {
// 确认本进程不再使用 cosClient 实例之后,关闭之
cosClient.shutdown();
}
return objectExists;
}
/**
* 删除
*/
public static void delete(String key) {
new Thread(new Runnable() {
public void run() {
// 指定要删除的 bucket 和路径
try {
cosClient.deleteObject(bucketName, key);
log.info("删除成功");
} catch (Throwable tb) {
log.info("删除文件失败");
tb.printStackTrace();
}
}
}).start();
}
}
@@ -0,0 +1,39 @@
package com.jero.config.oss;
import com.jero.common.util.oss.CosBootUtil;
import com.jero.common.util.oss.OssBootUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @Author: liyawei
* @Description:
* @Date: Created in 9:11 2022/6/8
*/
@Configuration
public class CosConfiguration {
@Value("${jero.cos.secretId}")
private String secretId;
@Value("${jero.cos.secretKey}")
private String secretKey;
@Value("${jero.cos.region}")
private String region;
@Value("${jero.cos.bucketName}")
private String bucketName;
@Value("${jero.cos.appId}")
private String appId;
@Value("${jero.cos.endPoint}")
private String endPoint;
@Bean
public void initCosBootConfiguration() {
CosBootUtil.setSecretId(secretId);
CosBootUtil.setSecretKey(secretKey);
CosBootUtil.setRegion(region);
CosBootUtil.setBucketName(bucketName);
CosBootUtil.setAppId(appId);
CosBootUtil.setEndPoint(endPoint);
}
}