若依框架(前后端分离)集成腾讯云COS指南

使用腾讯云COS的优势

集成第三方对象存储服务如腾讯云COS,可以为若依框架带来以下优势:

  • 高可靠性:提供稳定、安全的文件存储服务。
  • 高可扩展性:支持弹性扩展,适应不同规模的应用需求。
  • 节省资源:减轻服务器存储压力,降低成本。
  • 高速传输:提高文件上传和下载速度,提升用户体验。

腾讯云COS简介

腾讯云COS(Cloud Object Storage)是一种高可靠、低延迟的对象存储服务。它支持弹性伸缩,可以存储各种类型的数据,并提供便捷的访问方式。

集成步骤

1. 添加腾讯云依赖

ruoyi-common/pom.xml中添加腾讯云COS的依赖:

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

2. 配置COS参数

ruoyi-admin/src/main/resources/application.yml中配置COS的必要参数:

tencent:
  cos:
    secret-id: your-secret-id
    secret-key: your-secret-key
    region: ap-guangzhou
    bucket-name: your-bucket-name
    prefix: your-folder-prefix # 可选
    base-url: https://your-bucket-name.cos.ap-guangzhou.myqcloud.com

3. 编写配置类

ruoyi-common/src/main/java/com/ruoyi/common/config中新建TencentCosConfig配置类:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class TencentCosConfig {
    @Value("${tencent.cos.secret-id}")
    private String secretId;

    @Value("${tencent.cos.secret-key}")
    private String secretKey;

    @Value("${tencent.cos.bucket-name}")
    private String bucketName;

    @Value("${tencent.cos.region}")
    private String region;

    @Value("${tencent.cos.base-url}")
    private String url;

    // Getters and Setters
}

4. 创建工具类

ruoyi-common/src/main/java/top/zsyp/common/utils/file/下创建TencentOssUploadUtils工具类,封装文件上传的逻辑:

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.model.CannedAccessControlList;
import com.qcloud.cos.model.ObjectMetadata;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.config.TencentCosConfig;
import com.ruoyi.common.utils.uuid.UUID;

import java.io.InputStream;

@Slf4j
@Component
public class TencentOssUploadUtils {

    private static TencentCosConfig tenantCosConfig;

    /**
     * 使用构造方法注入配置信息
     */
    @Autowired
    public TencentOssUploadUtils(TencentCosConfig tenantCosConfig) {
        TencentOssUploadUtils.tenantCosConfig = tenantCosConfig;
    }

    /**
     * 上传文件
     * @param file
     * @return
     * @throws Exception
     */
    public static String uploadFile(MultipartFile file) throws Exception {
        // 生成 OSSClient
        COSClient cosClient = initCos();
        // 原始文件名称
        String filename = file.getOriginalFilename();
        InputStream inputStream = file.getInputStream();
        String filePath = getFilePath(filename);
        try {
            // 设置上传文件信息
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(file.getSize());
            PutObjectRequest putObjectRequest = new PutObjectRequest(tenantCosConfig.getBucketName(), filePath, inputStream, objectMetadata);

            // 上传文件
            cosClient.putObject(putObjectRequest);
            cosClient.setBucketAcl(tenantCosConfig.getBucketName(), CannedAccessControlList.PublicRead);
            return tenantCosConfig.getUrl() + "/" + filePath;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            cosClient.shutdown();
        }
        return tenantCosConfig.getUrl() + "/" + filePath;
    }

    private static String getFilePath(String fileName){
        String filePath = "项目文件夹/";
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        filePath += UUID.randomUUID() + fileType;
        return filePath;
    }

    /**
     * 初始化COSClient
     * @return
     */
    private static COSClient initCos(){
        // 1 初始化用户身份信息
        BasicCOSCredentials credentials = new BasicCOSCredentials(tenantCosConfig.getSecretId(), tenantCosConfig.getSecretKey());
        // 2 设置 bucket 的区域
        Region region = new Region(tenantCosConfig.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        // 3 生成 cos 客户端。
        return new COSClient(credentials, clientConfig);
    }

}

5. 修改图片上传方法

前端
ruoyi-ui/src/components/ImageUpload/index.vue中将databaseUrl属性修改为空字符串,以直接使用腾讯云COS的URL:

baseUrl: "",

后端
ruoyi-admin/src/main/java/top/zsyp/web/controller/common/CommonController.java中修改通用上传方法uploadFile:  

    /**
     * 通用上传请求(单个)
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception
    {
        try
        {
            // 使用TencentOssUploadUtils上传文件并返回新文件名称
            String fileName = TencentOssUploadUtils.uploadFile(file);

            String url = fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

总结

这篇文章详细介绍了如何在若依框架中集成腾讯云COS(Cloud Object Storage)服务,以实现文件的持久化存储和访问。文章通过步骤化的指引,帮助开发者在若依框架中引入腾讯云COS依赖、配置COS参数、编写配置类和工具类、以及修改前后端的图片上传方法。整个流程包括引入COS依赖、在配置文件中设置COS的必要参数、编写配置类和工具类进行文件上传操作,最后在前后端分别调整上传方法以适配腾讯云COS。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值