Springboot整合Cos云存储

1、导入相关依赖

首先导入Cos云存储的相关依赖。

              <!--腾讯云COS-->
        <dependency>
            <groupId>com.tencentcloudapi</groupId>
            <artifactId>tencentcloud-sdk-java</artifactId>
            <version>3.0.1</version>
        </dependency>
 
        <dependency>
            <groupId>com.qcloud</groupId>
            <artifactId>cos_api</artifactId>
            <version>5.6.8</version>
        </dependency>

2、编写配置类

首先需要获取相关配置参数,进入腾讯云对象存储,创建存储桶并进入所创建的存储桶。

 

 

public class CosConfig {
    //腾讯云账号秘钥
    private String secretId = "";
    //密码秘钥
    private String secretKey = "";
    //存储桶地区
    private String region="";
    //存储桶名称
    private String bucketName="";
    //存储桶访问路径
    private String path="";
​
    //初始化cos对象,配置相关配置信息
    @Bean
    public COSClient cosClient(){
        // 1 初始化用户身份信息(secretId, secretKey)。
        COSCredentials cred = new BasicCOSCredentials(this.secretId, this.secretKey);
        // 2 设置 bucket 的区域
        Region region = new Region(this.region);
        ClientConfig clientConfig = new ClientConfig(region);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }
}

3、编写逻辑层

        其实最好的方式是将Cos云配置信息放入application.properties或application.yml文件中,但我在之前配置的时候因为一些原因没这么配置,只好就这样写了,有兴趣的话可以自己配置到配置文件中,引用会更加方便。 详细信息直接看代码。

//在此编写你要实现的功能方法 
public interface ICosFileService {
    //文件批量上传
    public ReturnUtil upload(MultipartFile[] files);
    //文件删除
    void delete(String fileName);
}
@Service
public class CosFileServiceImpl implements ICosFileService {
    private String secretId = "";
​
    private String secretKey = "";
​
    private String region = "";
​
    private String bucketName = "";
​
    private String path = "";
​
    @Autowired
    private COSClient cosClient;
​
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ReturnUtil upload(MultipartFile[] files) {
        ReturnUtil responseDto = null;
        String res = "";
        try {
            for (MultipartFile file : files) {
                String originalfileName = file.getOriginalFilename();
                // 获得文件流
                InputStream inputStream = file.getInputStream();
                //设置文件key
                String filePath = getFileKey(originalfileName);
                // 上传文件
                cosClient.putObject(new PutObjectRequest(bucketName, filePath, inputStream, null));
                cosClient.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
                String url = path + "/" + filePath;
                res += url + ",";
            }
            String paths = res.substring(0, res.length() - 1);
            return new ReturnUtil(200, "成功并返回数据", paths);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cosClient.shutdown();
        }
        return responseDto;
    }
​
    /**
     * 生成文件路径
     *
     * @return
     */
    private String getFileKey(String originalfileName) {
        //获取后缀名  
        String fileType = originalfileName.substring(originalfileName.lastIndexOf("."));
        //以文件后缀来在存储桶中生成文件夹方便文件管理
        String filePath = fileType.substring(1, fileType.length()) + "/";
        //去除文件后缀 替换所有特殊字符
        String fileStr = StrUtil.removeSuffix(originalfileName, fileType).replaceAll("[^0-9a-zA-Z\\u4e00-\\u9fa5]", "_");
        filePath += new DateTime().toString("yyyyMMddHHmmss") + "_" + fileStr + fileType;
        return filePath;
    }
​
    @Override
    public void delete(String fileName) {
        CosConfig cosConfig = new CosConfig();
        cosConfig.cosClient();
        cosClient.deleteObject(this.bucketName, fileName);
    }
}
 

4、测试

编写Controller层代码测试方法。

   @Autowired
    private ICosFileService iCosFileService;
    @PostMapping("/test")
    public ReturnUtil test(@RequestParam("files") MultipartFile[] files){
        return iCosFileService.upload(files);
    }

 因为实现的是文件批量上传,当然单文件上传也没有问题,使用PostMan测试参数填写如上。

测试结果,因为我在多文件上传的时候将文件的访问路径以逗号隔开,有需要的话可以自己更改。

最后,delete方法就直接将上面文件生成的路径传进去就可以达到删除的效果了,我就不测试了。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
Spring Boot是一个用于快速构建Java应用程序的开发框架,而COS(腾讯对象存储)是一种存储服务。在Spring Boot中,我们可以通过一些配置和依赖来实现与COS整合。 首先,你需要在Spring Boot项目的pom.xml文件中添加COS SDK的依赖。可以使用以下代码片段: ```xml <dependency> <groupId>com.qcloud</groupId> <artifactId>cos_api</artifactId> <version>5.6.0</version> </dependency> ``` 接下来,你需要在Spring Boot的配置文件(application.properties或application.yml)中配置COS的相关信息,例如: ```properties cos.secretId=your-secret-id cos.secretKey=your-secret-key cos.bucketName=your-bucket-name cos.region=your-region ``` 然后,在你的Spring Boot应用程序中,你可以使用COS SDK提供的API来进行文件上传、下载等操作。你可以创建一个COSClient对象,并使用它来执行各种操作。以下是一个简单的示例: ```java import com.qcloud.cos.COSClient; import com.qcloud.cos.model.PutObjectRequest; import com.qcloud.cos.model.PutObjectResult; // ... @Autowired private COSClient cosClient; public void uploadFile(String filePath, String key) { PutObjectRequest request = new PutObjectRequest("your-bucket-name", key, new File(filePath)); PutObjectResult result = cosClient.putObject(request); // 处理上传结果... } ``` 以上代码示例中,我们使用了@Autowired注解将COSClient对象注入到Spring Boot的应用程序中,然后使用该对象执行文件上传操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值