早在课程开始阶段,我们就开通了腾讯云存储服务,只不过一直还没用上。这次咱们就要用一下这个云存储功能对请假单和病志做归档。
一、配置腾讯云存储
封装腾讯云存储之前,我们先要确定emos-api
项目中的application.yml
文件中已经定义好了云存储的各项值注入信息。
在pom.xml
文件中,我们已经引入了云存储用到的依赖库,所以接下来我们可以写代码封装云存储了。
<!--腾讯云存储-->
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>5.6.38</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.2.2</version>
</dependency>
二、封装云存储
腾讯云存储为我们提供很详细的API文档(https://cloud.tencent.com/document/product/436/10199),大家自学也能看的懂。
以后使用云存储的业务会有很多,所以我们要对业务场景加以区分。为了将来判断更方便,我定义了枚举类。创建com.example.emos.api.oss
包,然后在其中创建TypeEnum.java
枚举类。
public enum TypeEnum {
ARCHIVE("archive");
private String key;
private TypeEnum(String key) {
this.key = key;
}
private String getKey(){
return key;
}
public static TypeEnum findByKey(String key) {
if (key != null) {
for (TypeEnum type : TypeEnum.values()) {
if (key.equals(type.getKey())) {
return type;
}
}
}
return null;
}
}
在com.example.emos.api.oss
包中创建CosUtil.java
类,封装公共函数。
@Component
public class CosUtil {
@Value("${tencent.cloud.appId}")
private String appId;
@Value("${tencent.cloud.secretId}")
private String secretId;
@Value("${tencent.cloud.secretKey}")
private String secretKey;
@Value("${tencent.cloud.region}")
private String region;
@Value("${tencent.cloud.bucket}")
private String bucket;
private COSClient getCosClient() {
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
ClientConfig clientConfig = new ClientConfig(new Region(region));
clientConfig.setHttpProtocol(HttpProtocol.https);
COSClient cosClient = new COSClient(cred, clientConfig);
return cosClient;
}
public HashMap uploadFile(MultipartFile file, TypeEnum type) throws IOException {
String path = null; //文件将要存放的相对路径
String fileName = file.getOriginalFilename();
//根据传入的type判断放入哪个文件夹
if (type == type.ARCHIVE) {
path = "/archive/" + IdUtil.simpleUUID() + fileName.substring(fileName.lastIndexOf("."));
}
//元数据信息
ObjectMetadata meta = new ObjectMetadata();
meta.setContentLength(file.getSize());
meta.setContentEncoding("UTF-8");
meta.setContentType(file.getContentType());
//创建请求
PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, path, file.getInputStream(), meta);
// 设置存储类型, 默认是标准(Standard), 低频(Standard_IA)
putObjectRequest.setStorageClass(StorageClass.Standard);
//获取Client对象
COSClient client = getCosClient();
//发出请求,上传文件
PutObjectResult putObjectResult = client.putObject(putObjectRequest);
//上传结束后关闭Client
client.shutdown();
HashMap map=new HashMap();
//刚刚上传文件的外网访问地址
map.put("url","https://" + bucket + ".cos." + region + ".myqcloud.com" + path);
//文件的相对路径
map.put("path",path);
return map;
}
public void deleteFile(String[] pathes) {
COSClient client = getCosClient();
for (String path : pathes) {
client.deleteObject(bucket, path);
}
client.shutdown();
}
}
三、定义Web层代码
创建DeleteCosFileForm.java
类,用于封装Ajax提交的数据。
@Data
@Schema(description = "删除腾讯云COS文件表单")
public class DeleteCosFileForm {
@NotEmpty(message = "pathes不能为空")
private String[] pathes;
}
创建CosController.java
类,声明Web方法。
@RestController
@RequestMapping("/cos")
@Slf4j
@Tag(name = "CosController", description = "对象存储Web接口")
public class CosController {
@Autowired
private CosUtil cosUtil;
@PostMapping("/uploadCosFile")
@SaCheckLogin
@Operation(summary = "上传文件")
public R uploadCosFile(@Param("file") MultipartFile file, @Param("type") String type) {
TypeEnum typeEnum = TypeEnum.findByKey(type);
if (typeEnum == null) {
throw new EmosException("type类型错误");
}
try {
HashMap map=cosUtil.uploadFile(file, typeEnum);
return R.ok(map);
} catch (IOException e) {
log.error("文件上传到腾讯云错误", e);
throw new EmosException("文件上传到腾讯云错误");
}
}
@PostMapping("/deleteCosFile")
@SaCheckLogin
@Operation(summary = "删除文件")
public R deleteCosFile(@Valid @RequestBody DeleteCosFileForm form) {
cosUtil.deleteFile(form.getPathes());
return R.ok();
}
}