腾讯云COS对象存储使用记录及实现图片上传

开通服务

为什么不用阿里云的OSS,或者华为云的OBS,因为他们都要收费啊hhh,而且腾讯云COS有半年免费50G的存储服务。

创建存储桶

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

创建密钥

在这里插入图片描述
在这里插入图片描述

SpringBoot下配置COS

在这里插入图片描述
SecretId 是你生成的密钥ID,Key是密码,region是地区,url是访问域名,bucketName是桶名

创建测试类

先测一下能不能用,在单元测试中添加

@RunWith(SpringRunner.class)
@SpringBootTest(classes = COSTest.class)
public class COSTest {

    @Value("${spring.tengxun.SecretId}")
    private String secretId;

    @Value("${spring.tengxun.SecretKey}")
    private String secretKey;

    @Value("${spring.tengxun.region}")
    private String region;

    @Value("${spring.tengxun.bucketName}")
    private String bucketName;

    @Value("${spring.tengxun.url}")
    private String path;

    private COSClient cosClient;

    @Before
    public void init(){
        // 1 初始化用户身份信息(secretId, secretKey)。
        String secretId = this.secretId;
        String secretKey = this.secretKey;
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region(this.region);
        ClientConfig clientConfig = new ClientConfig(region);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        this.cosClient = cosClient;
    }

    /**
     * 查询存储桶列表
     */
    @Test
    public void queryBucket(){
        try {
            List<Bucket> buckets = cosClient.listBuckets();
            System.out.println(buckets);
        } catch (CosServiceException serverException) {
            serverException.printStackTrace();
        } catch (CosClientException clientException) {
            clientException.printStackTrace();
        }
    }

    /**
     * 上传文件
     */
    @Test
    public void upLoad(){
        try {
            // 指定要上传的文件
            File localFile = new File("E:\\Desktop\\test.txt");
            // 指定要上传到的存储桶
            String bucketName = this.bucketName;
            // 指定要上传到 COS 上对象键
            String key = "exampleobject";
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
            PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            System.out.println(putObjectResult.getDateStr());
        } catch (CosServiceException serverException) {
            serverException.printStackTrace();
        } catch (CosClientException clientException) {
            clientException.printStackTrace();
        }
    }

    /**
     * 下载文件
     */
    @Test
    public void download(){
        try{
            // 指定对象所在的存储桶
            String bucketName = this.bucketName;
            // 指定对象在 COS 上的对象键
            String key = "exampleobject";
            // 指定要下载到的本地路径
            File downFile = new File("E:\\Desktop\\download\\downloadFile");
            GetObjectRequest getObjectRequest = new GetObjectRequest(bucketName, key);
            ObjectMetadata downObjectMeta = cosClient.getObject(getObjectRequest, downFile);
        } catch (CosServiceException serverException) {
            serverException.printStackTrace();
        } catch (CosClientException clientException) {
            clientException.printStackTrace();
        }
    }

    /**
     * 查询存储桶中对象列表
     */
    @Test
    public void queryBucketPojo(){
        try{
            ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
            // 设置 bucket 名称
            listObjectsRequest.setBucketName(this.bucketName);
            // prefix 表示列出的 object 的 key 以 prefix 开始
            listObjectsRequest.setPrefix("");
            // 设置最大遍历出多少个对象, 一次 listobject 最大支持1000
            listObjectsRequest.setMaxKeys(1000);
            listObjectsRequest.setDelimiter("/");
            ObjectListing objectListing = cosClient.listObjects(listObjectsRequest);
            for (COSObjectSummary cosObjectSummary : objectListing.getObjectSummaries()) {
                // 对象的路径 key
                String key = cosObjectSummary.getKey();
                // 对象的 etag
                String etag = cosObjectSummary.getETag();
                // 对象的长度
                long fileSize = cosObjectSummary.getSize();
                // 对象的存储类型
                String storageClass = cosObjectSummary.getStorageClass();
                System.out.println("key:" + key + "; etag:" + etag + "; fileSize:" + fileSize + "; storageClass:" + storageClass);
            }
        }catch (CosServiceException serverException){
            serverException.printStackTrace();
        }catch (CosClientException clientException){
            clientException.printStackTrace();
        }
    }

    /**
     * 删除指定对象
     */
    @Test
    public void delBucketPojo(){
        try {
            // 指定对象所在的存储桶
            String bucketName = this.bucketName;
            // 指定对象在 COS 上的对象键
            String key = "exampleobject";
            cosClient.deleteObject(bucketName, key);
        } catch (CosServiceException serverException) {
            serverException.printStackTrace();
        } catch (CosClientException clientException) {
            clientException.printStackTrace();
        }
    }

    @After
    public void clear(){
        // 关闭客户端(关闭后台线程)
        cosClient.shutdown();
    }

}

测试都是通过的。

创建配置类

/**
 * 腾讯云COS配置
 */
@Configuration
@Data
public class TC_COS_Config {

    @Value("${spring.tengxun.SecretId}")
    private String secretId;

    @Value("${spring.tengxun.SecretKey}")
    private String secretKey;

    @Value("${spring.tengxun.region}")
    private String region;

    @Value("${spring.tengxun.bucketName}")
    private String bucketName;

    @Value("${spring.tengxun.url}")
    private String path;


    @Bean
    public COSClient cosClient(){
        // 1 初始化用户身份信息(secretId, secretKey)。
        COSCredentials cred = new BasicCOSCredentials(this.secretId, this.secretKey);
        // 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region(this.region);
        ClientConfig clientConfig = new ClientConfig(region);
        // 3 生成 cos 客户端。
        COSClient cosClient = new COSClient(cred, clientConfig);
        return cosClient;
    }


}

定义后台响应格式

/**
 * 该类用于返回给前端的数据结构定义。
 */
@Data
public class PicUploadResult {
    // 文件唯一标识
    private String uid;

    // 文件名
    private String name;

    // 状态有:uploading done error removed
    private String status;

    // 服务端响应内容,如:'{"status": "success"}'
    private String response;
}

创建图片上传服务

/**
 * 图片上传服务
 * 上传至腾讯云COS(对象存储中心)
 */
@Service
public class PicUploadService {

    @Autowired
    private COSClient cosClient;

    @Autowired
    private TC_COS_Config tc_cos_config;

    // 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".gif", ".png"};

    public PicUploadResult upload(MultipartFile uploadFile){
        // 校验图片格式
        boolean isLegal = false;
        for(String type : IMAGE_TYPE){
            if(StringUtils.endsWithIgnoreCase(uploadFile.getOriginalFilename(),type)){
                isLegal = true;
                break;
            }
        }
        // 封装Result对象,并且将文件的byte数组放置到result对象中
        PicUploadResult fileUploadResult = new PicUploadResult();
        if(!isLegal){
            fileUploadResult.setStatus("error:illegal file");
            return fileUploadResult;
        }

        // 文件新路径
        String fileName = uploadFile.getOriginalFilename();
        String filePath = getFilePath(fileName);

        //上传文件
        try {

            // 指定要上传到的存储桶
            String bucketName = tc_cos_config.getBucketName();
            // 指定要上传到 COS 上对象键
            String key = filePath;
            //PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, new ByteArrayInputStream(uploadFile.getBytes()));
            //PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
            //这里的key是查找文件的依据,妥善保管
            cosClient.putObject(bucketName,key,new ByteArrayInputStream(uploadFile.getBytes()),null);
            //设置输出信息
            fileUploadResult.setStatus("done");
            fileUploadResult.setName(this.tc_cos_config.getPath()+filePath);
            System.out.println(this.tc_cos_config.getPath()+filePath);
            fileUploadResult.setUid(String.valueOf(System.currentTimeMillis()));
            return fileUploadResult;
        }
        catch (Exception e){
            e.printStackTrace();
            fileUploadResult.setStatus("error: uploadFail");
            return fileUploadResult;
        }

    }

    /**
     * 删除某个图片
     * @param key
     */
    public boolean deletePic(String key){
        try {
            // 指定对象所在的存储桶
            String bucketName = this.tc_cos_config.getBucketName();
            cosClient.deleteObject(bucketName, key);
            return true;
        } catch (CosServiceException serverException) {
            serverException.printStackTrace();
            return false;
        } catch (CosClientException clientException) {
            clientException.printStackTrace();
            return false;
        }
    }

    /**
     * 生成文件路径
     * @param sourceFileName
     * @return
     */
    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/"
                + dateTime.toString("yyyy") + "/" + dateTime.toString("MM")
                + "/" + dateTime.toString("dd")
                + "/" + System.currentTimeMillis()
                + RandomUtils.nextInt(100, 9999) + "."
                + StringUtils.substringAfterLast(sourceFileName, ".");
    }
}

编写Controller

    @PostMapping("/upload")
    @ResponseBody
    @ApiOperation(value = "上传图片",notes = "POST")
    public PicUploadResult upload(@RequestParam("file")MultipartFile multipartFile) throws Exception{
        return this.picUploadService.upload(multipartFile);
    }

Swagger测试

在这里插入图片描述
这里的name就是访问链接
在这里插入图片描述
这样,就完成了图片上传的功能。

猜你喜欢

转载自blog.csdn.net/weixin_41154636/article/details/97968374
今日推荐