若依前后端分离版 集成 腾讯云 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

相关推荐
容器魔方12 小时前
Volcano v1.16 发布:新增 NamespaceQueue 与 fairshare,拓展 HyperNode 生态
人工智能·云原生·容器·华为云·云计算
hz5678912 小时前
本地部署视频会议系统软件功能有哪些?会议预约、权限分配与协作能力详解
安全·云计算·实时音视频·信息与通信·远程工作
GPU实战笔记15 小时前
A100 按量实例转长期计费前,需要确认哪些条件?
云计算·a100·按量计费·实例生命周期·gpu实例
无风听海19 小时前
AWS CLI的profile
云计算·aws
翼龙云_cloud1 天前
亚马逊云服务器服务代理商:Bedrock 实践经验 Serverless 架构下的 AI 自动化落地
服务器·架构·serverless·云计算·aws
GPU实战笔记1 天前
实例节点选择:创建入口与运行时稳定性的边界
云计算·a100·gpu 实例·节点选择·工作流验证
mengge.cloud2 天前
1019Namespace ,Contexts ,Kubernetes Pod
运维·服务器·网络·云原生·容器·kubernetes·云计算
云老大-阿里云国际站代理商2 天前
网站遇到恶意爬虫和CC攻击,阿里云国际站WAF与Bot管理怎么搭配
爬虫·阿里云·云计算
着迷不白2 天前
生产环境标准的Linux系统安装到服务器
linux·云计算
Geek-Chow3 天前
01 · Why AWS Lambda: Idle Cost, Capacity Planning and Risky In-Place Deploys
云计算