一. 什么是对象存储
- 腾讯云叫COS,在阿里云叫OSS,是一样的
- 对象存储(Cloud Object Storage,COS)是腾讯云提供的一种存储海量文件的分布式存储服务,具有高扩展性、低成本、可靠安全等优点。通过控制台、API、SDK 和工具等多样化方式,用户可简单、快速地接入 COS,进行多格式文件的上传、下载和管理,实现海量数据存储和管理。
二. 相关配置项
- 从密钥管理查看accessKey/secretKey
三. 代码实现
POM依赖
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
COS配置文件
bucketName: test-1254123199
path: https://test-1254123199.cos.ap-nanjing.myqcloud.com
COS配置类
@ConfigurationProperties(prefix = "spring.tencent")
private String accesskey;
private String secretKey;
private String bucketName;
控制器
@RequestMapping(value = "/upload")
public class UploadController {
@PostMapping(value = "/tencent")
public Object upload(@RequestParam(value = "file") MultipartFile file) {
return new UploadMsg(0, "文件为空", null);
String oldFileName = file.getOriginalFilename();
String suffix = oldFileName.substring(oldFileName.lastIndexOf("."));
String newFileName = UUID.randomUUID() + suffix;
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DATE);
// 1 初始化用户身份信息(secretId, secretKey)
COSCredentials cred = new BasicCOSCredentials(ossConfig.getAccesskey(), ossConfig.getSecretKey());
// 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
ClientConfig clientConfig = new ClientConfig(new Region(ossConfig.getBucket()));
COSClient cosclient = new COSClient(cred, clientConfig);
// bucket的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
String bucketName = ossConfig.getBucketName();
// 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20 M 以下的文件使用该接口
// 大文件上传请参照 API 文档高级 API 上传
localFile = File.createTempFile("temp", null);
file.transferTo(localFile);
String key = "/" + ossConfig.getPreffix() + "/" + year + "/" + month + "/" + day + "/" + newFileName;
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
return new UploadMsg(1, "上传成功", ossConfig.getPath() + putObjectRequest.getKey());
} catch (IOException e) {
return new UploadMsg(-1, e.getMessage(), null);
private class UploadMsg {
public UploadMsg(int status, String msg, String path) {
上传验证