1、POM依赖
<!--腾讯云COS-->
<dependency>
<groupId>com.tencentcloudapi</groupId>
<artifactId>tencentcloud-sdk-java</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>5.4.9</version>
</dependency>
2、涉及代码
2.1 配置类
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @Description 腾讯云COS相关配置文件
* @Author Jason
* @Date 2020/3/5 16:22
* @Email jasonaszp@163.com
*/
@Data
@ConfigurationProperties(prefix = "tencentcos")
@Component
public class TencentCosConfig {
//腾讯云的SecretId
private String secretId;
//腾讯云的SecretKey
private String secretKey;
//腾讯云的bucket (存储桶)
private String bucket;
//腾讯云的region(bucket所在地区)
private String region;
//腾讯云的allowPrefix(允许上传的路径)
private String allowPrefix = "*";
//腾讯云的临时密钥时长(单位秒)
private String durationSeconds;
//腾讯云的访问基础链接:
private String baseUrl;
}
2.2 具体上传逻辑代码
import com.etc.insurance.config.TencentCosConfig;
import com.etc.util.EtcSpringUtils;
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.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.StorageClass;
import com.qcloud.cos.region.Region;
import java.io.*;
/**
* @Description 腾讯云cos服务器上传工具类
* @Author Jason
* @Date 2020/3/6 14:30
* @Email jasonaszp@163.com
*/
public class TencentUploadUtil {
//腾讯云的SecretId
private static String secretId;
//腾讯云的SecretKey
private static String secretKey;
//腾讯云的bucket (存储桶)
private static String bucket;
//腾讯云的region(bucket所在地区)
private static String region;
//腾讯云的allowPrefix(允许上传的路径)
private static String allowPrefix;
//腾讯云的临时密钥时长(单位秒)
private static String durationSeconds;
//腾讯云的访问基础链接:
private static String baseUrl;
// 腾讯云cos相关配置类
private static TencentCosConfig tencentCosConfig;
//初始化配置
static {
tencentCosConfig = EtcSpringUtils.getBean(TencentCosConfig.class);
secretId = tencentCosConfig.getSecretId();
secretKey = tencentCosConfig.getSecretKey();
bucket = tencentCosConfig.getBucket();
region = tencentCosConfig.getRegion();
allowPrefix = tencentCosConfig.getAllowPrefix();
durationSeconds = tencentCosConfig.getDurationSeconds();
baseUrl = tencentCosConfig.getBaseUrl();
}
/**
* 上传腾讯云
*
* @param bytes 文件字节
* @param filePath 文件路径
* @return 腾讯云访问路径
*/
public static String upload(byte[] bytes, String filePath) {
// 1 初始化秘钥信息
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2 设置bucket的区域
ClientConfig clientConfig = new ClientConfig(new Region(region));
// 3 生成cos客户端
COSClient cosClient = new COSClient(cred, clientConfig);
// 处理文件路径
filePath = filePath.startsWith("/") ? filePath : "/" + filePath;
// 判断文件大小(小文件上传建议不超过20M)
int length = bytes.length;
// 获取文件流
InputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
ObjectMetadata objectMetadata = new ObjectMetadata();
// 从输入流上传必须制定content length, 否则http客户端可能会缓存所有数据,存在内存OOM的情况
objectMetadata.setContentLength(length);
// 默认下载时根据cos路径key的后缀返回响应的contenttype, 上传时设置contenttype会覆盖默认值
// objectMetadata.setContentType("image/jpeg");
PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, filePath, byteArrayInputStream, objectMetadata);
// 设置 Content type, 默认是 application/octet-stream
putObjectRequest.setMetadata(objectMetadata);
// 设置存储类型, 默认是标准(Standard), 低频(standard_ia)
putObjectRequest.setStorageClass(StorageClass.Standard_IA);
PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
String eTag = putObjectResult.getETag();
System.out.println(eTag);
// 关闭客户端
cosClient.shutdown();
// http://{buckname}-{appid}.cosgz.myqcloud.com/image/1545012027692.jpg
return baseUrl + filePath;
}
/**
* 上传腾讯云
*
* @param file 文件
* @param filePath 文件路径
* @return 腾讯云访问路径
*/
public static String upload(File file, String filePath) {
// 1 初始化秘钥信息
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
ClientConfig clientConfig = new ClientConfig(new Region(region));
// 3 生成cos客户端
COSClient cosClient = new COSClient(cred, clientConfig);
// 处理文件路径
filePath = filePath.startsWith("/") ? filePath : "/" + filePath;
// 判断文件大小(小文件上传建议不超过20M)
byte[] bytes = File2byte(file);
int length = bytes.length;
// 获取文件流
InputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
ObjectMetadata objectMetadata = new ObjectMetadata();
// 从输入流上传必须制定content length, 否则http客户端可能会缓存所有数据,存在内存OOM的情况
objectMetadata.setContentLength(length);
// 默认下载时根据cos路径key的后缀返回响应的contenttype, 上传时设置contenttype会覆盖默认值
// objectMetadata.setContentType("image/jpeg");
PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, filePath, byteArrayInputStream, objectMetadata);
// 设置 Content type, 默认是 application/octet-stream
putObjectRequest.setMetadata(objectMetadata);
// 设置存储类型, 默认是标准(Standard), 低频(standard_ia)
putObjectRequest.setStorageClass(StorageClass.Standard_IA);
PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
String eTag = putObjectResult.getETag();
System.out.println(eTag);
// 关闭客户端
cosClient.shutdown();
// http://{buckname}-{appid}.cosgz.myqcloud.com/image/1545012027692.jpg
return baseUrl + filePath;
}
public static byte[] File2byte(File tradeFile) {
byte[] buffer = null;
try {
FileInputStream fis = new FileInputStream(tradeFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
buffer = bos.toByteArray();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return buffer;
}
}