若依前后端分离版 集成 腾讯云 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集成XXL-JOB实现任务管理全流程

《SpringBoot集成XXL-JOB实现任务管理全流程》XXL-JOB是一款轻量级分布式任务调度平台,功能丰富、界面简洁、易于扩展,本文介绍如何通过SpringBoot项目,使用RestTempl... 目录一、前言二、项目结构简述三、Maven 依赖四、Controller 代码详解五、Service

springboot2.1.3 hystrix集成及hystrix-dashboard监控详解

《springboot2.1.3hystrix集成及hystrix-dashboard监控详解》Hystrix是Netflix开源的微服务容错工具,通过线程池隔离和熔断机制防止服务崩溃,支持降级、监... 目录Hystrix是Netflix开源技术www.chinasem.cn栈中的又一员猛将Hystrix熔

Spring Security 前后端分离场景下的会话并发管理

《SpringSecurity前后端分离场景下的会话并发管理》本文介绍了在前后端分离架构下实现SpringSecurity会话并发管理的问题,传统Web开发中只需简单配置sessionManage... 目录背景分析传统 web 开发中的 sessionManagement 入口ConcurrentSess

MyBatis-Plus 与 Spring Boot 集成原理实战示例

《MyBatis-Plus与SpringBoot集成原理实战示例》MyBatis-Plus通过自动配置与核心组件集成SpringBoot实现零配置,提供分页、逻辑删除等插件化功能,增强MyBa... 目录 一、MyBATis-Plus 简介 二、集成方式(Spring Boot)1. 引入依赖 三、核心机制

SpringBoot集成P6Spy的实现示例

《SpringBoot集成P6Spy的实现示例》本文主要介绍了SpringBoot集成P6Spy的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录本节目标P6Spy简介抛出问题集成P6Spy1. SpringBoot三板斧之加入依赖2. 修改

springboot项目中集成shiro+jwt完整实例代码

《springboot项目中集成shiro+jwt完整实例代码》本文详细介绍如何在项目中集成Shiro和JWT,实现用户登录校验、token携带及接口权限管理,涉及自定义Realm、ModularRe... 目录简介目的需要的jar集成过程1.配置shiro2.创建自定义Realm2.1 LoginReal

SpringBoot集成Shiro+JWT(Hutool)完整代码示例

《SpringBoot集成Shiro+JWT(Hutool)完整代码示例》ApacheShiro是一个强大且易用的Java安全框架,提供了认证、授权、加密和会话管理功能,在现代应用开发中,Shiro因... 目录一、背景介绍1.1 为什么使用Shiro?1.2 为什么需要双Token?二、技术栈组成三、环境

Java 与 LibreOffice 集成开发指南(环境搭建及代码示例)

《Java与LibreOffice集成开发指南(环境搭建及代码示例)》本文介绍Java与LibreOffice的集成方法,涵盖环境配置、API调用、文档转换、UNO桥接及REST接口等技术,提供... 目录1. 引言2. 环境搭建2.1 安装 LibreOffice2.2 配置 Java 开发环境2.3 配

MySQL中读写分离方案对比分析与选型建议

《MySQL中读写分离方案对比分析与选型建议》MySQL读写分离是提升数据库可用性和性能的常见手段,本文将围绕现实生产环境中常见的几种读写分离模式进行系统对比,希望对大家有所帮助... 目录一、问题背景介绍二、多种解决方案对比2.1 原生mysql主从复制2.2 Proxy层中间件:ProxySQL2.3

SpringBoot集成EasyExcel实现百万级别的数据导入导出实践指南

《SpringBoot集成EasyExcel实现百万级别的数据导入导出实践指南》本文将基于开源项目springboot-easyexcel-batch进行解析与扩展,手把手教大家如何在SpringBo... 目录项目结构概览核心依赖百万级导出实战场景核心代码效果百万级导入实战场景监听器和Service(核心