Spring Boot上传文件到腾讯云储存

腾讯云平台操作

登录到腾讯云控制台 -> 对象存储 -> 创建存储桶(访问权限设置为公有读私有写)

1
2
3
空间名称    appblog-1253563213
所属地域 广州(华南) (ap-guangzhou)
访问域名 https://appblog-1253563213.cos.ap-guangzhou.myqcloud.com

秘钥管理 -> 新建云API秘钥

1
2
SecretId: AKIDhBQQAjuGA6MehUITeZDbjcGessc9st88
SecretKey: L2JK6JHEySV3LgmZSWehXAYsxoQn75kA

Spring boot项目集成

Maven依赖

1
2
3
4
5
6
<!-- https://mvnrepository.com/artifact/com.qcloud/cos_api -->
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>5.5.1</version>
</dependency>

配置信息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
tencent:
#腾讯云存储所需信息
cloud:
#SecretId
accessKey: AKIDhBQQAjuGA6MehUITeZDbjcGessc9st88
#SecretKey
secretKey: L2JK6JHEySV3LgmZSWehXAYsxoQn75kA
#所属区域
bucket: ap-guangzhou
#存储桶名称
bucketName: appblog-1253563213
#访问域名
path: https://appblog-1253563213.cos.ap-guangzhou.myqcloud.com
#路径前缀
prefix: appblog
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Getter
@Setter
@Configuration
public class TencentConfig {
@Value("${tencent.cloud.accessKey}")
private String accessKey;
@Value("${tencent.cloud.secretKey}")
private String secretKey;
@Value("${tencent.cloud.bucket}")
private String bucket;
@Value("${tencent.cloud.bucketName}")
private String bucketName;
@Value("${tencent.cloud.path}")
private String path;
@Value("${tencent.cloud.prefix}")
private String prefix;
}

文件上传控制器

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
@Controller
@Slf4j
@RequestMapping(value = "/upload/tencent")
public class TencentUploadController {
@Autowired
private TencentConfig tencentConfig;

/**
* 上传道腾讯云服务器(https://cloud.tencent.com/document/product/436/10199)
* @return
*/
@RequestMapping(value = "/single", method = RequestMethod.POST)
@ResponseBody
public Object Upload(@RequestParam(value = "file") MultipartFile file, HttpSession session) {
if (file == null) {
return new UploadMsg(0, "文件为空", null);
}
String oldFileName = file.getOriginalFilename();
String eName = oldFileName.substring(oldFileName.lastIndexOf("."));
String newFileName = UUID.randomUUID() + eName;
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH) + 1;
int day = cal.get(Calendar.DATE);
// 1 初始化用户身份信息(secretId, secretKey)
COSCredentials cred = new BasicCOSCredentials(tencentConfig.getAccessKey(), tencentConfig.getSecretKey());
// 2 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
ClientConfig clientConfig = new ClientConfig(new Region(tencentConfig.getBucket()));
// 3 生成cos客户端
COSClient cosclient = new COSClient(cred, clientConfig);
// bucket的命名规则为{name}-{appid} ,此处填写的存储桶名称必须为此格式
String bucketName = tencentConfig.getBucketName();

// 简单文件上传, 最大支持 5 GB, 适用于小文件上传, 建议 20 M 以下的文件使用该接口
// 大文件上传请参照 API 文档高级 API 上传
File localFile = null;
try {
localFile = File.createTempFile("temp", null);
file.transferTo(localFile);
// 指定要上传到 COS 上的路径
String key = "/" + tencentConfig.getPrefix() + "/" + year + "/" + month + "/" + day + "/" + newFileName;
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
PutObjectResult putObjectResult = cosclient.putObject(putObjectRequest);
log.info(putObjectResult.getContentMd5());
log.info(putObjectResult.getDateStr());
log.info(putObjectResult.getETag());
log.info(putObjectResult.getRequestId());
//{"status":1,"msg":"上传成功","path":"https://appblog-1253563213.cos.ap-guangzhou.myqcloud.com/appblog/2019/2/20/3f934239-2c92-4da1-bb80-896299fcdcdf.png"}
return new UploadMsg(1, "上传成功", tencentConfig.getPath() + putObjectRequest.getKey());
} catch (IOException e) {
return new UploadMsg(-1, e.getMessage(), null);
} finally {
// 关闭客户端(关闭后台线程)
cosclient.shutdown();
}
}
}
1
2
3
4
5
6
7
8
9
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
public class UploadMsg {
public int status;
public String msg;
public String path;
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :