使用腾讯云COS的优势
集成第三方对象存储服务如腾讯云COS,可以为若依框架带来以下优势:
- 高可靠性:提供稳定、安全的文件存储服务。
- 高可扩展性:支持弹性扩展,适应不同规模的应用需求。
- 节省资源:减轻服务器存储压力,降低成本。
- 高速传输:提高文件上传和下载速度,提升用户体验。
腾讯云COS简介
腾讯云COS(Cloud Object Storage)是一种高可靠、低延迟的对象存储服务。它支持弹性伸缩,可以存储各种类型的数据,并提供便捷的访问方式。
集成步骤
1. 添加腾讯云依赖
在ruoyi-common/pom.xml
中添加腾讯云COS的依赖:
<dependency>
<groupId>com.qcloud</groupId>
<artifactId>cos_api</artifactId>
<version>5.6.29</version>
</dependency>
2. 配置COS参数
在ruoyi-admin/src/main/resources/application.yml
中配置COS的必要参数:
tencent:
cos:
secret-id: your-secret-id
secret-key: your-secret-key
region: ap-guangzhou
bucket-name: your-bucket-name
prefix: your-folder-prefix # 可选
base-url: https://your-bucket-name.cos.ap-guangzhou.myqcloud.com
3. 编写配置类
在ruoyi-common/src/main/java/com/ruoyi/common/config
中新建TencentCosConfig
配置类:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class TencentCosConfig {
@Value("${tencent.cos.secret-id}")
private String secretId;
@Value("${tencent.cos.secret-key}")
private String secretKey;
@Value("${tencent.cos.bucket-name}")
private String bucketName;
@Value("${tencent.cos.region}")
private String region;
@Value("${tencent.cos.base-url}")
private String url;
// Getters and Setters
}
4. 创建工具类
在ruoyi-common/src/main/java/top/zsyp/common/utils/file/
下创建TencentOssUploadUtils
工具类,封装文件上传的逻辑:
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 lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.config.TencentCosConfig;
import com.ruoyi.common.utils.uuid.UUID;
import java.io.InputStream;
@Slf4j
@Component
public class TencentOssUploadUtils {
private static TencentCosConfig tenantCosConfig;
/**
* 使用构造方法注入配置信息
*/
@Autowired
public TencentOssUploadUtils(TencentCosConfig tenantCosConfig) {
TencentOssUploadUtils.tenantCosConfig = tenantCosConfig;
}
/**
* 上传文件
* @param file
* @return
* @throws Exception
*/
public static String uploadFile(MultipartFile file) throws Exception {
// 生成 OSSClient
COSClient cosClient = initCos();
// 原始文件名称
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 = "项目文件夹/";
String fileType = fileName.substring(fileName.lastIndexOf("."));
filePath += UUID.randomUUID() + fileType;
return filePath;
}
/**
* 初始化COSClient
* @return
*/
private static COSClient initCos(){
// 1 初始化用户身份信息
BasicCOSCredentials credentials = new BasicCOSCredentials(tenantCosConfig.getSecretId(), tenantCosConfig.getSecretKey());
// 2 设置 bucket 的区域
Region region = new Region(tenantCosConfig.getRegion());
ClientConfig clientConfig = new ClientConfig(region);
// 3 生成 cos 客户端。
return new COSClient(credentials, clientConfig);
}
}
5. 修改图片上传方法
前端
在ruoyi-ui/src/components/ImageUpload/index.vue
中将data
的baseUrl
属性修改为空字符串,以直接使用腾讯云COS的URL:
baseUrl: "",
后端
在ruoyi-admin/src/main/java/top/zsyp/web/controller/common/CommonController.java
中修改通用上传方法uploadFile
:
/**
* 通用上传请求(单个)
*/
@PostMapping("/upload")
public AjaxResult uploadFile(MultipartFile file) throws Exception
{
try
{
// 使用TencentOssUploadUtils上传文件并返回新文件名称
String fileName = TencentOssUploadUtils.uploadFile(file);
String url = fileName;
AjaxResult ajax = AjaxResult.success();
ajax.put("url", url);
ajax.put("fileName", fileName);
ajax.put("newFileName", FileUtils.getName(fileName));
ajax.put("originalFilename", file.getOriginalFilename());
return ajax;
}
catch (Exception e)
{
return AjaxResult.error(e.getMessage());
}
}
总结
这篇文章详细介绍了如何在若依框架中集成腾讯云COS(Cloud Object Storage)服务,以实现文件的持久化存储和访问。文章通过步骤化的指引,帮助开发者在若依框架中引入腾讯云COS依赖、配置COS参数、编写配置类和工具类、以及修改前后端的图片上传方法。整个流程包括引入COS依赖、在配置文件中设置COS的必要参数、编写配置类和工具类进行文件上传操作,最后在前后端分别调整上传方法以适配腾讯云COS。