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

发布于:2024-05-01 ⋅ 阅读:(23) ⋅ 点赞:(0)

原因:

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

步骤:

  • 添加腾讯云依赖 

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

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

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

        <tencent.cos.version>5.6.89</tencent.cos.version>
  • 设置COS的必要参数

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

        方式二:直接在代码中配置COS参数(我是用的这个方式)

在公共模块中建立Bean

ruoyi-common->src->main->java->com->ruoyi->common->config->TencentCosConfig.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

为参数赋值

    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

    /**
     * 初始化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);
    }

创建  上传文件  方法

   /**
     * 上传文件
     * @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;
    }

完整的方法

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 

        通用上传请求(单个)

    /**
     * 通用上传请求(单个)
     */
    @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

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

 baseUrl: "",

Over