(亲测有效)SpringBoot项目集成腾讯云COS对象存储(1)

目录

一、腾讯云对象存储使用

1、创建Bucket

2、使用web控制台上传和浏览文件

3、创建API秘钥

二、代码对接腾讯云COS(以Java为例)

1、初始化客户端

2、填写配置文件

3、通用能力类

文件上传

测试


一、腾讯云对象存储使用

1、创建Bucket

(1)进入腾讯云官网,注册登录用户,进行实名认证,开通“对象存储COS”服务,进入管理控制台,

(2)进入管理控制台,找到存储桶列表, 创建存储桶。

可以把存储桶理解为一个存储空间,和文件系统类似,都是根据路径找到文件或目录(比如/test/aaajpg )。可以多个项目共用一个存储桶,也可以每个项目一个。

点击创建存储桶,注意地域选择国内(离用户较近的位置)。此处访问权限先选择"公有读私有写”,因为我们的存储桶要存储允许用户公开访问的代码生成器图片。而如果整个存储桶要存储的文件都不允许用户访问,建议选择私有读写,更安全。

默认告警一定要勾选!因为对象存储服务的存储和访问流量都是计费的,超限后我们要第一时间得到通知并进行相应的处理。

不过也不用太担心,自己做项目的话一般是没人攻击你的,而且对象存储很便宜,正常情况下消耗的费用寥寥无几。

然后一直点击“下一步"即可。

2、使用web控制台上传和浏览文件

开通成功后,我们可以试着使用web控制台上传和浏览文件。

先上传一个文件,点击上传。

上传文件后,可以使用对象存储服务为我们生成的默认域名,在线访问图片。

当然,一般情况下我们会使用程序来操作存储桶。

3、创建API秘钥

进入访问管理中的访问密钥里的API秘钥管理,地址为登录 - 腾讯云

点击新建秘钥,

 

二、代码对接腾讯云COS(以Java为例)

1、初始化客户端

参考官方文档,我们要先初始化一个 COS 客户端对象,和对象存储服务进行交互。

对于我们的项目,只需要复用一个COS 客户端对象即可,所以我们可以通过编写配置类初始化客户端对象。

1)使用idea打开后端项目,在 config 目录下新建 CosClientConfig 类,负责读取配置文件。并创建一个COS 客户端的 Bean。

代码如下:

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.region.Region;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 腾讯云对象存储客户端
 */
@Configuration
@ConfigurationProperties(prefix = "cos.client")
@Data
public class CosClientConfig {
    private String accessKey;

    private String secretKey;

    /**
     * 区域
     */
    private String region;

    /**
     * 桶名
     */
    private String bucket;

    @Bean
    public COSClient cosClient() {
        // 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(accessKey, secretKey);
        // 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
        ClientConfig clientConfig = new ClientConfig(new Region(region));
        // 生成cos客户端
        return new COSClient(cred, clientConfig);
    }
}

2、填写配置文件

一定要注意防止密码泄露!所以我们新建application-local.yml文件,并且在.gitignore中忽略该文件的提交,这样就不会将代码等敏感配置提交到代码仓库了。

配置代码如下:

# 对象存储
# todo 需替换配置
cos:
  client:
    accessKey: xxx
    secretKey: xxx
    region: xxx
    bucket: xxx

可以通过如下方式分别获取需要的配置。

(1)accessKey/secretId、secretKey 密钥对:在腾讯云网站中,访问管理中的密钥管理中获取。

获取地址为:登录 - 腾讯云

(2)region 表示地域名,默认域名指 COS 的默认存储桶域名,腾讯云中,用户在 创建存储桶 时,由系统根据存储桶名称和地域自动生成。不同地域的存储桶有不同的默认域名。

获取地址为:对象存储 地域和访问域名-产品简介-文档中心-腾讯云

此处我的regin域名应该是ap-beijing。 

 (3)bucket是存储桶名,可以从腾讯云网站的对象存储里,点击存储桶列表里获取。

 写完配置文件之后,如下图所示,

 

3、通用能力类

我们新建 CosManager 类,提供通用的对象存储操作,比如文件上传、文件下载等,供其他代码(比如 Service)调用。

文件上传

参考官方文档的"上传对象"部分,可以编写出文件上传的代码。地址 : https://cloud.tencent.com/document/product/436/65935

CosManager 新增两个上传对象的方法,代码如下:

import com.qcloud.cos.COSClient;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.model.PutObjectResult;
import com.waterai.water.config.CosClientConfig;
import java.io.File;
import javax.annotation.Resource;
import org.springframework.stereotype.Component;

/**
 * Cos 对象存储操作
 */
@Component
public class CosManager {

    @Resource
    private CosClientConfig cosClientConfig;

    @Resource
    private COSClient cosClient;

    /**
     * 上传对象
     * @param key 唯一键
     * @param localFilePath 本地文件路径
     * @return
     */
    public PutObjectResult putObject(String key, String localFilePath) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key, new File(localFilePath));
        return cosClient.putObject(putObjectRequest);
    }

    /**
     * 上传对象
     * @param key 唯一键
     * @param file 文件
     * @return
     */
    public PutObjectResult putObject(String key, File file) {
        PutObjectRequest putObjectRequest = new PutObjectRequest(cosClientConfig.getBucket(), key, file);
        return cosClient.putObject(putObjectRequest);
    }
}

(2)新建FileConstant类,设置常量中的 COS 访问域名,便于接下来测试访问已上传的文件。

代码如下:

/**
 * 文件常量
 */
public interface FileConstant {
    /**
     * COS 访问地址
     * todo 需替换配置
     */
    String COS_HOST = "https://xxxx.cos.ap-xxxx.myqcloud.com";
}

该域名可以在COS控制台的域名信息部分找到,

测试

(1为了方便测试,在 FileController 中编写测试文件上传接口。

核心流程是先接受用户上传的文件,指定上传的路径,然后调用 cosManager.putObject 方法上传文件到 COS 对象存储。上传成功后,会返回一个文件的key(其实就是文件路径),便于我们访问和下载文件。

需要注意,测试接口一定要加上管理员权限!防止任何用户随意上传文件。

测试文件上传接口这个方法的代码如下:

import cn.hutool.core.io.FileUtil;
import com.waterai.water.annotation.AuthCheck;
import com.waterai.water.common.BaseResponse;
import com.waterai.water.common.ErrorCode;
import com.waterai.water.common.ResultUtils;
import com.waterai.water.constant.FileConstant;
import com.waterai.water.constant.UserConstant;
import com.waterai.water.exception.BusinessException;
import com.waterai.water.manager.CosManager;
import com.waterai.water.model.dto.file.UploadFileRequest;
import com.waterai.water.model.entity.User;
import com.waterai.water.model.enums.FileUploadBizEnum;
import com.waterai.water.service.UserService;
import java.io.File;
import java.util.Arrays;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件接口
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {
    @Resource
    private UserService userService;

    @Resource
    private CosManager cosManager;

    /*
    * 其他方法。。。。。
    * */

    /*
    * 测试文件上传
    * */
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    @PostMapping("/test/upload")
    public BaseResponse<String> testUploadFile(@RequestPart("file") MultipartFile multipartFile) {
        // 文件目录
        String filename = multipartFile.getOriginalFilename();
        String filepath = String.format("/test/%s", filename);
        File file = null;
        try {
            //上传文件
            file = File.createTempFile(filepath, null);
            multipartFile.transferTo(file);
            cosManager.putObject(filepath, file);
            //返回可访问地址
            return ResultUtils.success(filepath);
        } catch (Exception e) {
            System.out.println("file upload error, filepath = " + filepath + ", error = " +e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            if (file != null) {
                //删除临时文件
                boolean delete = file.delete();
                if (!delete) System.out.println("file delete error, filepath = [l" + filepath);
            }
        }
    }
}

 (2)修改启动配置李的active profiles,使用local配置启动项。

然后点击启动按钮启动项目。

(2)打开 Swagger接口文档,此处我的项目端口是8101,因此就是http://localhost:8101/api/doc.html,然后在file-controller中找到测试文件上传的这个接口,开始进行测试。

首先,点击选择文件,从本地选择一个文件,然后点击发送请求。

请求返回成功。

(3)在腾讯云官网上的控制台中,可以看到已经有了test这个文件夹,双击进入,

就可以看到5.jpg这个文件已经上传成功了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水w

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值