腾讯云COS介绍
腾讯云COS(Cloud Object Storage)是一种基于对象的存储服务,用于存储和管理海量的非结构化数据,如图片、音视频文件、备份数据等。它具有以下特点和优势:
此外,腾讯云COS还广泛应用于以下场景:
总的来说,腾讯云COS是一种高可靠、低成本、弹性扩展的云存储服务,适用于各种需要存储和管理海量非结构化数据的场景。
后台管理系统需要有图片等文字上传功能,如图。
通过腾讯的OSS组件进行文件的上传。
1、pom文件引入腾讯云cos maven依赖
com.qcloud
cos_api
${cos_api.version}
版本可使用:
2、编写配置类。获取cos的相关配置,
相关配置包括域名、地域节点,存储桶 ,秘钥等购买腾讯云时分配的信息。与及要上传的文件相关信息要求。
@Data
@Component
@ConfigurationProperties(prefix = "oss.tencent")
public class TencentProperties {
/**域名*/
private String domain;
/**地域节点*/
private String region;
/**存储桶名称*/
private String bucketName;
/**secretId*/
private String secretId;
/**secretKey*/
private String secretKey;
/**图片策略*/
private String styleRule;
/**缩略图策略*/
private String thumbnailStyleRule;
/**文件类型*/
private List fileTypes;
}
3、文件上传下载处理类编写
@Slf4j
@Component("tencent")
public class TencentFileHandle implements FileStrategy {
@Autowired
TencentProperties tencentProperties;
// 创建 COSClient 实例,这个实例用来后续调用请求
COSClient createCOSClient() {
// 设置用户身份信息。
// SECRETID 和 SECRETKEY 请登录访问管理控制台 https://console.cloud.tencent.com/cam/capi 进行查看和管理
String secretId = tencentProperties.getSecretId();
String secretKey = tencentProperties.getSecretKey();
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// ClientConfig 中包含了后续请求 COS 的客户端设置:
ClientConfig clientConfig = new ClientConfig();
// 设置 bucket 的地域
// COS_REGION 请参照 https://cloud.tencent.com/document/product/436/6224
clientConfig.setRegion(new Region(tencentProperties.getRegion()));
// 设置请求协议, http 或者 https
// 5.6.53 及更低的版本,建议设置使用 https 协议
// 5.6.54 及更高版本,默认使用了 https
clientConfig.setHttpProtocol(HttpProtocol.https);
// 以下的设置,是可选的:
// 设置 socket 读取超时,默认 30s
clientConfig.setSocketTimeout(30*1000);
// 设置建立连接超时,默认 30s
clientConfig.setConnectionTimeout(30*1000);
// 如果需要的话,设置 http 代理,ip 以及 port
// clientConfig.setHttpProxyIp("httpProxyIp");
// clientConfig.setHttpProxyPort(80);
// 生成 cos 客户端。
return new COSClient(cred, clientConfig);
}
// 创建 TransferManager 实例,这个实例用来后续调用高级接口
TransferManager createTransferManager() {
// 创建一个 COSClient 实例,这是访问 COS 服务的基础实例。
// 详细代码参见本页: 简单操作 -> 创建 COSClient
COSClient cosClient = createCOSClient();
// 自定义线程池大小,建议在客户端与 COS 网络充足(例如使用腾讯云的 CVM,同地域上传 COS)的情况下,设置成16或32即可,可较充分的利用网络资源
// 对于使用公网传输且网络带宽质量不高的情况,建议减小该值,避免因网速过慢,造成请求超时。
ExecutorService threadPool = Executors.newFixedThreadPool(32);
// 传入一个 threadpool, 若不传入线程池,默认 TransferManager 中会生成一个单线程的线程池。
TransferManager transferManager = new TransferManager(cosClient, threadPool);
// 设置高级接口的配置项
// 分块上传阈值和分块大小分别为 5MB 和 1MB
TransferManagerConfiguration transferManagerConfiguration = new TransferManagerConfiguration();
transferManagerConfiguration.setMultipartUploadThreshold(5*1024*1024);
transferManagerConfiguration.setMinimumUploadPartSize(1*1024*1024);
transferManager.setConfiguration(transferManagerConfiguration);
return transferManager;
}
void shutdownTransferManager(TransferManager transferManager) {
// 指定参数为 true, 则同时会关闭 transferManager 内部的 COSClient 实例。
// 指定参数为 false, 则不会关闭 transferManager 内部的 COSClient 实例。
transferManager.shutdownNow(true);
}
@Override
public UploadDto upload(MultipartFile file) throws Exception {
return upload(file, null);
}
@Override
public UploadDto upload(MultipartFile file, String filePath) throws Exception {
//文件名
String fileFullName = FileUtil.getName(file.getOriginalFilename());
InputStream inputStream = file.getInputStream();
return upload(inputStream, fileFullName, filePath);
}
public UploadDto upload(InputStream inputStream, String fileFullName, String filePath) throws Exception {
if (inputStream == null) {
throw new Exception("上传文件不能为空");
}
TransferManager transferManager = createTransferManager();
String bucketName = tencentProperties.getBucketName();
//int inputStreamLength = 1024 * 1024;
// byte data[] = new byte[inputStreamLength];
// InputStream inputStream = new ByteArrayInputStream(data);
ObjectMetadata objectMetadata = new ObjectMetadata();
// 上传的流如果能够获取准确的流长度,则推荐一定填写 content-length
// 如果确实没办法获取到,则下面这行可以省略,但同时高级接口也没办法使用分块上传了
//objectMetadata.setContentLength(inputStreamLength);
try {
//时间戳
String timestamp = String.valueOf(System.currentTimeMillis());
//文件扩展名
String extension = FileUtil.getSuffix(fileFullName);
String fileName = FileUtil.getPrefix(fileFullName);
List fileTypes = tencentProperties.getFileTypes();
if(fileTypes != null) {
boolean flag= fileTypes.contains(extension);
Assert.isTrue(flag, "不支持上传的文件类型:" + extension);
}
String upFilePath = StringUtils.join(fileName, "_", timestamp, ".", extension);
if(filePath != null) {
upFilePath = StringUtils.join(filePath, "/", upFilePath);
}
String key = upFilePath;
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream, objectMetadata);
// 高级接口会返回一个异步结果Upload
// 可同步地调用 waitForUploadResult 方法等待上传完成,成功返回UploadResult, 失败抛出异常
Upload upload = transferManager.upload(putObjectRequest);
UploadResult uploadResult = upload.waitForUploadResult();
if (uploadResult == null) {
log.error("上传附件到腾讯云失败 fileName={}", upFilePath);
throw new Exception("上传附件 " + upFilePath + " 到腾讯云失败 ");
}
log.info("cos fileName:" + upFilePath);
//返回上传结果
UploadDto uploadDto = new UploadDto();
uploadDto.setName(upFilePath);
// uploadDto.setKey(upFilePath);
uploadDto.setCreateTime(DateUtil.date());
return uploadDto;
} catch (Exception e) {
log.error("cos 上传失败", e);
throw new RuntimeException("文件="+fileFullName + " 上传失败");
} finally {
shutdownTransferManager(transferManager);
}
}
@Override
public byte[] download(String key) throws Exception {
return null;
}
@Override
public void delete(String key) {
}
}
4、图片相关信息类
@Data
public class UploadDto implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
/**图片名*/
private String name;
/**图片路径*/
private String imgUrl;
// /**key*/
// private String key;
// /**图片跳转路径*/
// private String targetUrl;
/**上传日期*/
@JsonFormat(pattern = "yyyy-MM-dd")
private Date createTime;
}
5、调用
/**
* 图片上传
* 图片上传至OSS
*
* @param file 文件流
* @return ResponseData
* @throws Exception
*/
@ApiOperation(value = "图片上传至OSS", notes = "图片上传至OSS")
@PostMapping("upload")
public ResponseData upload(@RequestPart("file") MultipartFile file, @RequestHeader(name="ossType") String ossType) throws Exception {
// Assert.notNull(ossType, "资源类型不能为空");
if (file.getSize()/1024 > 10*1024) {
return ResponseData.error("资源为:" + (file.getSize()/1024/1024) + "M,大小超出限制的10M");
}
OssTypeEnum ossTypeEnum = null;
try {
if(ossType != null)
ossTypeEnum = OssTypeEnum.valueOf(ossType);
} catch (RuntimeException e) {
return ResponseData.error("资源类型不存在:" + ossType);
}
//上传至OSS
UploadDto dto = uploadService.upload(file, ossTypeEnum);
if (ObjectUtil.isNotEmpty(dto)) {
return ResponseData.success(dto);
} else {
log.error(MShuffleConstant.UPLOAD_FAILED);
return ResponseData.error(MShuffleConstant.UPLOAD_FAILED);
}
}
相关配置说明:
腾讯云COS(Cloud Object Storage)的配置主要涉及到创建存储桶、设置访问权限、配置数据传输等方面。以下是一个基本的腾讯云COS配置说明: