Java版cos文件操作(可直接 cv,开箱即用)

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);
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值