SpringBoot与腾讯COS连接

介绍

本文主要介绍了如何使用Springboot与腾讯云COS建立连接,完成上传、下载等基本操作

添加相关依赖

<dependency>
    <groupId>com.qcloud</groupId>
    <artifactId>cos_api</artifactId>
    <version>5.6.177</version>
</dependency>

配置相关信息

以application.yml为例

spring:
  cos:
    baseUrl: https://xxxx.myqcloud.com
    accessKey: xxxx
    secretKey: xxxx
    regionName: ap-beijing
    bucketName: xxxx
    folderPrefix: /files/
  servlet:
    multipart:
      max-file-size: 5MB
      max-request-size: 5MB

完成相关类

配置工具类

@Data
@Component
@ConfigurationProperties(prefix = "spring.cos")
public class MyCOSConfig
{
    private String baseUrl;
    private String accessKey;
    private String secretKey;
    private String regionName;
    private String bucketName;
    private String folderPrefix;

}

实现上传、删除、下载

上传核心代码:

@Service
public class OSSUploadServiceImpl implements OSSUploadService
{
    final MyCOSConfig myCOSConfig;

    public OSSUploadServiceImpl(MyCOSConfig myCOSConfig)
    {
        this.myCOSConfig = myCOSConfig;
    }

    @Override
    public Map<String, String> upload(MultipartFile multipartFile)
    {
        String fileName = multipartFile.getOriginalFilename();
        String key = myCOSConfig.getFolderPrefix() + fileName;
        return getStringStringMap(multipartFile, fileName, key);
    }

    /**
     *
     * @param prefix 前缀
     * @param multipartFile 文件
     * @return Map
     */
    @Override
    public Map<String, String> uploadHomework(String prefix, MultipartFile multipartFile)
    {
        String fileName = multipartFile.getOriginalFilename();
        String key = "/" + prefix + "/" + fileName;

        return getStringStringMap(multipartFile, fileName, key);
    }

    /**
     * 上传核心
     * @param multipartFile 文件
     * @param fileName 地址
     * @param key key
     * @return Map
     */
    private Map<String, String> getStringStringMap(MultipartFile multipartFile, String fileName, String key)
    {
        COSClient cosClient = null;

        Map<String, String> map = new HashMap<>();

        File file;
        try
        {
            file = File.createTempFile("temp",null);
            multipartFile.transferTo(file);

            COSCredentials cosCredentials = new BasicCOSCredentials(myCOSConfig.getAccessKey(), myCOSConfig.getSecretKey());
            ClientConfig clientConfig = new ClientConfig(new Region(myCOSConfig.getRegionName()));
            cosClient = new COSClient(cosCredentials, clientConfig);
            PutObjectRequest putObjectRequest = new PutObjectRequest(myCOSConfig.getBucketName(), key, file);
            cosClient.putObject(putObjectRequest);

            map.put("url", myCOSConfig.getBaseUrl()+key);
            map.put("fileName", fileName);
            return map;
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (cosClient != null)
            {
                cosClient.shutdown();
            }
        }

        return null;
    }
}

删除核心代码:

@Service
public class OSSDeleteServiceImpl implements OSSDeleteService
{
    final MyCOSConfig myCOSConfig;

    public OSSDeleteServiceImpl(MyCOSConfig myCOSConfig)
    {
        this.myCOSConfig = myCOSConfig;
    }

    @Override
    public boolean delete(String fileName)
    {
        String key = myCOSConfig.getFolderPrefix() + fileName;

        return deleteFile(key);
    }

    @Override
    public boolean deleteHomeworkFile(String prefix, String fileName)
    {
        // 这里传入的桶里的路径
        String key = prefix + "/" + fileName;
        return deleteFile(key);
    }

    private boolean deleteFile(String key)
    {
        COSClient cosclient;
        try
        {
            COSCredentials cosCredentials = new BasicCOSCredentials(myCOSConfig.getAccessKey(), myCOSConfig.getSecretKey());
            ClientConfig clientConfig = new ClientConfig(new Region(myCOSConfig.getRegionName()));
            cosclient = new COSClient(cosCredentials, clientConfig);
            cosclient.deleteObject(myCOSConfig.getBucketName(), key);

            cosclient.shutdown();

            return true;
        }
        catch (CosClientException e)
        {
            e.printStackTrace();
        }

        return false;
    }
}

下载核心代码:

此处实际上是获得先关文档的下载url,对于设置桶为私有读写的可以使用此类,增加安全性。如果桶为共有读写可以直接从数据库中获得文件的相关链接

@Service
public class OSSDownloadServiceImpl implements OSSDownloadService
{
    final MyCOSConfig myCOSConfig;

    public OSSDownloadServiceImpl(MyCOSConfig myCOSConfig)
    {
        this.myCOSConfig = myCOSConfig;
    }

    @Override
    public Map<String, Object> download(String fileName)
    {
        String key = myCOSConfig.getFolderPrefix() + fileName;

        return getStringObjectMap(key);
    }


    /**
     * 下载附件
     * @param prefix 前缀
     * @param fileName 文件名
     * @return Map
     */
    @Override
    public Map<String, Object> downloadHomework(String prefix, String fileName)
    {
        String key = "/" + prefix + "/" + fileName;

        return getStringObjectMap(key);
    }

    /**
     * 下载核心
     * @param key key
     * @return Map
     */
    private Map<String, Object> getStringObjectMap(String key)
    {
        Map<String, Object> map = new HashMap<>();

        COSClient cosclient;
        try
        {
            COSCredentials cosCredentials = new BasicCOSCredentials(myCOSConfig.getAccessKey(), myCOSConfig.getSecretKey());
            ClientConfig clientConfig = new ClientConfig(new Region(myCOSConfig.getRegionName()));
            cosclient = new COSClient(cosCredentials, clientConfig);

            Date expirationDate = new Date(System.currentTimeMillis() + 10 * 60 * 1000);

            URL url = cosclient.generatePresignedUrl(myCOSConfig.getBucketName(), key, expirationDate);

            map.put("url", url);

            cosclient.shutdown();

            return map;
        }
        catch (CosClientException e)
        {
            e.printStackTrace();
        }

        return null;
    }
}

下面是直接下载文件到本地服务器,需要首先配置COSCMD工具,可以参考
COSCMD工具

配置完成后如果想实现后端服务器调用命令行命令下载文件,可以使用如下代码

{
    //下载到本地
    // newPath 为桶内的相对路径
    // 然后紧跟" path"为服务器内下载的地址
    ProcessBuilder processBuilder = new ProcessBuilder("bash", "-c", "coscmd download " + newPath + " ~/" + path);
    try
    {
        processBuilder.start();
    }
    catch (IOException e)
    {
        throw new RuntimeException(e);
    }
}

SpringBoot与腾讯COS连接
https://dreamerland.cn/2023/12/28/springboot/Springboot与腾讯COS连接/
作者
Silva31
发布于
2023年12月28日
许可协议