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

2024-05-01 04:28
文章标签 分离 集成 腾讯 cos 若依

本文主要是介绍若依前后端分离版 集成 腾讯云 COS,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

原因:

        最近在根据一个若依二开的项目继续进行开发,当添加到轮播图模块的时候,涉及到了图片上传,由于公司以前一直使用的是腾讯云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;/*** 使用构造方法注入配置信息*/@Autowiredpublic 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;/*** 使用构造方法注入配置信息*/@Autowiredpublic 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中出现devapibaseUrl: "",

Over

 

这篇关于若依前后端分离版 集成 腾讯云 COS的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/950717

相关文章

SpringBoot实现数据库读写分离的3种方法小结

《SpringBoot实现数据库读写分离的3种方法小结》为了提高系统的读写性能和可用性,读写分离是一种经典的数据库架构模式,在SpringBoot应用中,有多种方式可以实现数据库读写分离,本文将介绍三... 目录一、数据库读写分离概述二、方案一:基于AbstractRoutingDataSource实现动态

springboot security之前后端分离配置方式

《springbootsecurity之前后端分离配置方式》:本文主要介绍springbootsecurity之前后端分离配置方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的... 目录前言自定义配置认证失败自定义处理登录相关接口匿名访问前置文章总结前言spring boot secu

springboot简单集成Security配置的教程

《springboot简单集成Security配置的教程》:本文主要介绍springboot简单集成Security配置的教程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,... 目录集成Security安全框架引入依赖编写配置类WebSecurityConfig(自定义资源权限规则

springboot集成Deepseek4j的项目实践

《springboot集成Deepseek4j的项目实践》本文主要介绍了springboot集成Deepseek4j的项目实践,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价... 目录Deepseek4j快速开始Maven 依js赖基础配置基础使用示例1. 流式返回示例2. 进阶

Spring Boot 集成 Quartz 使用Cron 表达式实现定时任务

《SpringBoot集成Quartz使用Cron表达式实现定时任务》本文介绍了如何在SpringBoot项目中集成Quartz并使用Cron表达式进行任务调度,通过添加Quartz依赖、创... 目录前言1. 添加 Quartz 依赖2. 创建 Quartz 任务3. 配置 Quartz 任务调度4. 启

Spring AI集成DeepSeek三步搞定Java智能应用的详细过程

《SpringAI集成DeepSeek三步搞定Java智能应用的详细过程》本文介绍了如何使用SpringAI集成DeepSeek,一个国内顶尖的多模态大模型,SpringAI提供了一套统一的接口,简... 目录DeepSeek 介绍Spring AI 是什么?Spring AI 的主要功能包括1、环境准备2

Spring AI集成DeepSeek实现流式输出的操作方法

《SpringAI集成DeepSeek实现流式输出的操作方法》本文介绍了如何在SpringBoot中使用Sse(Server-SentEvents)技术实现流式输出,后端使用SpringMVC中的S... 目录一、后端代码二、前端代码三、运行项目小天有话说题外话参考资料前面一篇文章我们实现了《Spring

SpringBoot集成图片验证码框架easy-captcha的详细过程

《SpringBoot集成图片验证码框架easy-captcha的详细过程》本文介绍了如何将Easy-Captcha框架集成到SpringBoot项目中,实现图片验证码功能,Easy-Captcha是... 目录SpringBoot集成图片验证码框架easy-captcha一、引言二、依赖三、代码1. Ea

C#集成DeepSeek模型实现AI私有化的流程步骤(本地部署与API调用教程)

《C#集成DeepSeek模型实现AI私有化的流程步骤(本地部署与API调用教程)》本文主要介绍了C#集成DeepSeek模型实现AI私有化的方法,包括搭建基础环境,如安装Ollama和下载DeepS... 目录前言搭建基础环境1、安装 Ollama2、下载 DeepSeek R1 模型客户端 ChatBo

JAVA集成本地部署的DeepSeek的图文教程

《JAVA集成本地部署的DeepSeek的图文教程》本文主要介绍了JAVA集成本地部署的DeepSeek的图文教程,包含配置环境变量及下载DeepSeek-R1模型并启动,具有一定的参考价值,感兴趣的... 目录一、下载部署DeepSeek1.下载ollama2.下载DeepSeek-R1模型并启动 二、J