若依前后端分离版 集成 腾讯云 COS

原因:

最近在根据一个若依二开的项目继续进行开发,当添加到轮播图模块的时候,涉及到了图片上传,由于公司以前一直使用的是腾讯云COS(不是阿里云OSS),在网上搜索一番后,没有找到 若依前后端分离版 COS 关键字的文章,只能根据阿里云OSS的文章进行模仿集成。

步骤:

添加腾讯云依赖

在根pom.xml中(最外层的pom文件)添加依赖

java 复制代码
            <!--        Tencent COS-->
            <dependency>
                <groupId>com.qcloud</groupId>
                <artifactId>cos_api</artifactId>
                <version>${tencent.cos.version}</version>
            </dependency>

由于我使用的是 5.6.89 的版本,因此需要在 properties 标签中添加版本信息

java 复制代码
        <tencent.cos.version>5.6.89</tencent.cos.version>

设置COS的必要参数

方式一:使用配置文件的方式设置COS参数(我没有使用这种方式,而是直接写死)

方式二:直接在代码中配置COS参数(我是用的这个方式)
在公共模块中建立Bean

ruoyi-common->src->main->java->com->ruoyi->common->config->TencentCosConfig.java

java 复制代码
@Component
public class TencentCosConfig {

    /**
     * AccessKey
     */
    private String secretId;

    /**
     * AccessKey秘钥
     */
    private String secretKey;

    /**
     * bucket名称
     */
    private String bucketName;

    /**
     * bucket下文件夹的路径
     */
    private String region;

    /**
     * 访问域名
     */
    private String url;

    public String getSecretId() {
        return secretId;
    }

    public void setSecretId(String secretId) {
        this.secretId = secretId;
    }

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public String getBucketName() {
        return bucketName;
    }

    public void setBucketName(String bucketName) {
        this.bucketName = bucketName;
    }

    public String getRegion() {
        return region;
    }

    public void setRegion(String region) {
        this.region = region;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }
}

在utils文件夹中新建oss文件夹,并在其内构建Utils工具类

ruoyi-common->src->main->java->com->ruoyi->common->utils->oss->TencentOssUploadUtils.java
为参数赋值

java 复制代码
    private static TencentCosConfig tenantCosConfig;


    /**
     * 使用构造方法注入配置信息
     */
    @Autowired
    public TencentOssUploadUtils(TencentCosConfig tenantCosConfig) {
        // 写死
        tenantCosConfig.setSecretId("A*****omY9i");
        tenantCosConfig.setSecretKey("*****w");
        tenantCosConfig.setBucketName("****6");
        tenantCosConfig.setRegion("ap-***");
        tenantCosConfig.setUrl("https://***.cos.ap-chongqing.myqcloud.com");
        TencentOssUploadUtils.tenantCosConfig = tenantCosConfig;
    }

初始化COSClient

java 复制代码
    /**
     * 初始化COSClient
     * @return
     */
    private static COSClient initCos(){
        // 1 初始化用户身份信息(secretId, secretKey)
        BasicCOSCredentials credentials = new BasicCOSCredentials(tenantCosConfig.getSecretId(), tenantCosConfig.getSecretKey());
        // 2 设置 bucket 的区域, COS 地域的简称请参照
        Region region = new Region(tenantCosConfig.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        // 从 5.6.54 版本开始,默认使用了 https
        // clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        return new COSClient(credentials, clientConfig);
    }

创建 上传文件 方法

java 复制代码
   /**
     * 上传文件
     * @param file
     * @return
     * @throws Exception
     */
    public static String uploadFile(MultipartFile file) throws Exception {

        // 生成 OSSClient
        //OSS ossClient = new OSSClientBuilder().build(tenantCosConfig.getEndpoint(), tenantCosConfig.getSecretId(), tenantCosConfig.getSecretKey());
        COSClient cosClient = initCos();
        // 原始文件名称
        // String originalFilename = file.getOriginalFilename();
        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;
    }

获取文件名方法

java 复制代码
    private static String getFilePath(String fileName){
        String filePath = "xinxun/";
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        filePath += RandomUtil.randomString(8) + fileType;
        return filePath;
    }

完整的方法

java 复制代码
package com.ruoyi.common.utils.oss;


import cn.hutool.core.util.RandomUtil;
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 com.ruoyi.common.config.TencentCosConfig;
import com.ruoyi.common.utils.file.FileUploadUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author zouhuu
 * @description 阿里云对象存储上传工具类
 * @date 2022/06/16 14:21:12
 */
@Slf4j
@Component
public class TencentOssUploadUtils {

    private static TencentCosConfig tenantCosConfig;


    /**
     * 使用构造方法注入配置信息
     */
    @Autowired
    public TencentOssUploadUtils(TencentCosConfig tenantCosConfig) {
        // 写死
        tenantCosConfig.setSecretId("A*****9i");
        tenantCosConfig.setSecretKey("J******CHCw");
        tenantCosConfig.setBucketName("****");
        tenantCosConfig.setRegion("ap-***");
        tenantCosConfig.setUrl("https://******ud.com");
        TencentOssUploadUtils.tenantCosConfig = tenantCosConfig;
    }

    /**
     * 上传文件
     * @param file
     * @return
     * @throws Exception
     */
    public static String uploadFile(MultipartFile file) throws Exception {

        // 生成 OSSClient
        //OSS ossClient = new OSSClientBuilder().build(tenantCosConfig.getEndpoint(), tenantCosConfig.getSecretId(), tenantCosConfig.getSecretKey());
        COSClient cosClient = initCos();
        // 原始文件名称
        // String originalFilename = file.getOriginalFilename();
        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 = "xinxun/";
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        filePath += RandomUtil.randomString(8) + fileType;
        return filePath;
    }

    /**
     * 初始化COSClient
     * @return
     */
    private static COSClient initCos(){
        // 1 初始化用户身份信息(secretId, secretKey)
        BasicCOSCredentials credentials = new BasicCOSCredentials(tenantCosConfig.getSecretId(), tenantCosConfig.getSecretKey());
        // 2 设置 bucket 的区域, COS 地域的简称请参照
        Region region = new Region(tenantCosConfig.getRegion());
        ClientConfig clientConfig = new ClientConfig(region);
        // 从 5.6.54 版本开始,默认使用了 https
        // clientConfig.setHttpProtocol(HttpProtocol.https);
        // 3 生成 cos 客户端。
        return new COSClient(credentials, clientConfig);
    }

}

修改图片上传方法

文件位置:

ruoyi-admin->src->main->java->com->ruoyi->web->controller->common->CommonController.java

通用上传请求(单个)

java 复制代码
    /**
     * 通用上传请求(单个)
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try
        {
            // 上传并返回新文件名称
            String url = TencentOssUploadUtils.uploadFile(file);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", FileUtils.getName(url));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

注意事项

当修改完若依后端之后,还需要修改前端的imageUpload

java 复制代码
// data里面 将baseUrl 的默认值改为"",不然就会在图片url中出现devapi

 baseUrl: "",

Over

相关推荐
HaoHao_0106 小时前
边缘安全加速平台 EO 套餐
云计算·腾讯云·加速·套餐
Marblog6 小时前
腾讯云DeepSeek大模型应用搭建指南
云计算·腾讯云
AI服务老曹9 小时前
确保设备始终处于最佳运行状态,延长设备的使用寿命,保障系统的稳定运行的智慧地产开源了
人工智能·开源·云计算·音视频
成长的小牛23311 小时前
阿里云k8s服务部署操作一指禅
阿里云·kubernetes·云计算
The丶Star18 小时前
阿里云百炼通义大模型
阿里云·云计算
好记忆不如烂笔头abc18 小时前
阿里云虚机的远程桌面登录提示帐户被锁定了
阿里云·云计算
ueotek18 小时前
Ansys 2025 R1 | 以强大数字工程技术增强协作,拓展云计算及AI并赋能数据洞察
人工智能·云计算·ansys
调皮的芋头19 小时前
【架构思维基础:如何科学定义问题】
大数据·阿里云·架构·云计算
G皮T1 天前
【弹性计算】IaaS 和 PaaS 类计算产品
阿里云·云计算·paas·iaas·云服务器·弹性服务器·弹性计算
alden_ygq1 天前
在阿里云Linux主机上运行大模型deepseek r1
linux·阿里云·云计算