文章目录
1. 配置 .yml
storage:
tencent:
#API密钥secretId
secretId: *******
#API密钥secretKey
secretKey: *******
#存储桶所属地域
region: ap-beijing
#存储桶空间名称(name + appId)
bucketName: demo-1311835527
#存储桶访问域名
url: https://demo-1311835527.cos.ap-beijing.myqcloud.com
#上传文件前缀路径(eg:/images/)
prefix: /images/
2. 配置 TencentConfig.java
@Data
@Configuration
@ConfigurationProperties(prefix = "storage.tencent")
public class TencentConfig {
private String url;
private String secretId;
private String secretKey;
private String region;
private String bucketName;
private String prefix;
// 注入 cos 客户端
@Bean
public COSClient cosClient() {
// System.out.println(secretId);
// 1. 初始化用户身份信息(secretId, secretKey)
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 2. 设置bucket的区域, COS地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
// clientConfig中包含了设置region, https(默认http), 超时, 代理等set方法, 使用可参见源码或者接口文档FAQ中说明
ClientConfig clientConfig = new ClientConfig(new Region(region));
// 3. 生成cos客户端
return new COSClient(cred, clientConfig);
}
}
3. 编写 TencentService.java
接口
@Service
public interface TencentService {
/**
* @description: 文件上传
* @param file 文件
* @return com.chuang.bootplus.base.utils.ApiResponse<java.util.Map<java.lang.String,java.lang.String>>
* @date: 2022/10/10 2:38
*/
ApiResponse<Map<String, String>> upload(MultipartFile file);
/**
* @param key 文件唯一标识
* @param fileName 文件名
* @param path 文件的保存路径
* @return com.chuang.bootplus.base.utils.ApiResponse<java.lang.String>
* @description: 文件下载
* @date: 2022/10/10 16:44
*/
ApiResponse<String> download(String key, String path, String fileName);
/**
* @description: 文件删除
* @param key 文件唯一 id
* @return com.chuang.bootplus.base.utils.ApiResponse<java.lang.Void>
* @date: 2022/10/10 2:39
*/
ApiResponse<Void> del(String key);
}
3. 编写接口实现类 TencentServiceImpl.java
/**
* @description: TODO 腾讯云文件操作
* @author nuo
* @date 2022/5/12 0:21
* @version 1.0
*/
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class TencentServiceImpl implements TencentService {
public final COSClient cosClient;
public final TencentConfig tencentConfig;
@Override
public ApiResponse<Map<String, String>> upload(MultipartFile file) {
if (ObjectUtil.isEmpty(file)) {
throw new BusException("上传文件为空, 请选择后上传!");
}
try {
String filename = file.getOriginalFilename();
String bucketName = tencentConfig.getBucketName();
String key = tencentConfig.getPrefix()
+ UUID.randomUUID().toString().replaceAll("-", "")
+ filename.substring(filename.lastIndexOf('.'));
//将 MultipartFile 类型 转为 File 类型
File localFile = File.createTempFile("temp", null);
file.transferTo(localFile);
cosClient.putObject(new PutObjectRequest(bucketName, key, localFile));
Map<String, String> map = new HashMap<>(1);
map.put("url", tencentConfig.getUrl() + key);
return new ApiResponse<>(map);
} catch (IOException e) {
throw new BusException(e.getMessage());
}
}
@Override
public ApiResponse<String> download(String key, String path, String fileName) {
TransferManager transferManager = null;
try {
//下载到本地指定路径
File localDownFile = new File(path + fileName);
GetObjectRequest getObjectRequest = new GetObjectRequest(tencentConfig.getBucketName(), tencentConfig.getPrefix() + key);
// 下载文件
transferManager = new TransferManager(cosClient);
Download download = transferManager.download(getObjectRequest, localDownFile);
// 等待传输结束 (如果想同步的等待上传结束,则调用 waitForCompletion)
download.waitForCompletion();
} catch (Throwable tb) {
tb.printStackTrace();
throw new BusException("下载失败...");
} finally {
// 关闭 TransferManger
assert transferManager != null;
transferManager.shutdownNow();
}
return new ApiResponse<>("下载成功...");
}
@Override
public ApiResponse<Void> del(String key) {
cosClient.deleteObject(tencentConfig.getBucketName(), tencentConfig.getPrefix() + key);
return new ApiResponse<>();
}
}
2. 测试文件的上传
、下载
、删除
/**
* @description: TODO Test 测试用
* @author nuo
* @date 2022/10/10 1:28
* @version 1.0
*/
@Api(tags = {"腾讯云"})
@RestController
@RequestMapping("storage/tencent")
@CrossOrigin
public class TencentDemoController {
@Autowired
TencentService tencentService;
@PostMapping("/upload")
@ApiOperation("上传...")
public ApiResponse<Map<String, String>> upload(MultipartFile file) {
return tencentService.upload(file);
}
@PostMapping("/download")
@ApiOperation("下载...")
@ApiImplicitParams({
@ApiImplicitParam(name = "key", value = "文件 id", example = "881f853eb9e34c0c8721b464c380f236.jpg"),
@ApiImplicitParam(name = "path", value = "文件的保存路径", example = "F:\\"),
@ApiImplicitParam(name = "fileName", value = "源文件名", example = "老实巴交.jpg")
})
public ApiResponse<String> download(String key, String path, String fileName) {
return tencentService.download(key, path, fileName);
}
@PostMapping("/del")
@ApiOperation("删除...")
@ApiImplicitParam(name = "key", value = "文件 id", example = "f5e75ec0eebf4d66bec4f5024276fa4f.jpg")
public ApiResponse<Void> del(String key) {
return tencentService.del(key);
}
}