oss封装插件

day-06
Saisai Liu 2024-02-27 21:39:37 +08:00
parent a51d27fb72
commit b7748c9606
10 changed files with 360 additions and 3 deletions

View File

@ -88,9 +88,14 @@
<version>${swagger.fox.version}</version>
</dependency>
<!-- <dependency>-->
<!-- <groupId>com.alibaba.csp</groupId>-->
<!-- <artifactId>sentinel-core</artifactId>-->
<!-- <version>1.8.7</version>-->
<!-- </dependency>-->
<dependency>
<groupId>com.alibaba.csp</groupId>
<artifactId>sentinel-core</artifactId>
<artifactId>sentinel-transport-simple-http</artifactId>
<version>1.8.7</version>
</dependency>

View File

@ -28,7 +28,7 @@ spring:
eager: true
transport:
# 控制台地址
dashboard: 127.0.0.1:8080
dashboard: 127.0.0.1:8858
# nacos配置持久化
datasource:
ds1:

View File

@ -67,6 +67,14 @@
<artifactId>muyu-common-system</artifactId>
</dependency>
<!--aliyun oos文件上传封装-->
<!-- 阿里云oss依赖 -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.12.0</version>
</dependency>
</dependencies>
<build>

View File

@ -0,0 +1,23 @@
package com.muyu.file.config;
public class OSSCloudConfig {
static final String ENDPOINT_INTER = "oss-cn-guangzhou-internal.aliyuncs.com"; //ECS 的经典网络访问(内网)
public static final String ENDPOINT = "oss-cn-guangzhou.aliyuncs.com"; //外网访问
public static final String ACCESSKEYID = "your accesskeyId";
public static final String ACCESSKEYSECRET = "your accesskeysecret";
public static final String BUCKETNAME = "your bucket name";
public String objectPrefixName = "static/images/"; //基础文件夹
public String filePathPrefix = "https://" + BUCKETNAME + "." + ENDPOINT + "/" + objectPrefixName; //带https的完整访问前缀
public String getObjectPrefixName() {
return objectPrefixName;
}
public void setObjectPrefixName(String objectPrefixName) {
this.objectPrefixName = objectPrefixName;
}
public String getFilePathPrefix() {
return filePathPrefix;
}
public void setFilePathPrefix(String filePathPrefix) {
this.filePathPrefix = filePathPrefix;
}
}

View File

@ -0,0 +1,12 @@
package com.muyu.file.service;
import org.springframework.web.multipart.MultipartFile;
/**
* @author Eric
* @create 2022-04-24 23:39
*/
public interface OssService {
//上传头像到oss
String uploadFileAvatar(MultipartFile file);
}

View File

@ -0,0 +1,64 @@
//package com.muyu.file.service;
//
//import com.aliyun.oss.OSS;
//import com.aliyun.oss.OSSClientBuilder;
//import com.muyu.file.utils.ConstantPropertiesUtil;
//import org.springframework.stereotype.Service;
//import org.springframework.web.multipart.MultipartFile;
//
//import java.io.InputStream;
//
///**
// * @author Eric
// * @create 2022-04-24 23:40
// */
//@Service
//public class OssServiceImpl implements OssService {
//
// //上传头像到oss
// @Override
// public String uploadFileAvatar(MultipartFile file) {
//
// //工具类获取值分别是地域节点、id、秘钥、项目名称
// String endpoint = ConstantPropertiesUtil.END_POINT;
// String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
// String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
// String bucketName = ConstantPropertiesUtil.BUCKET_NAME;
//
// try {
// // 创建OSS实例。
// OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
//
// //获取上传文件输入流
// InputStream inputStream = file.getInputStream();
// //获取文件名称
// String fileName = file.getOriginalFilename();
//
// //1、在文件名称里面添加随机唯一值因为如果上传文件名称相同的话后面的问价会将前面的文件给覆盖了
// String uuid = UUID.randomUUID().toString().replaceAll("-","");//因为生成后的值有横岗,我们就把它去除,不替换也可以,也没有错
// fileName = uuid + fileName;
//
// //2、把文件安装日期进行分类 2022/10/11/1.jpg
// //获取当前日期
// String datePath = new DateTime().toString("yyyy/MM/dd");//在依赖中引入了该工具类
//
// //拼接
// fileName = datePath + "/" + fileName;
//
// //调用oss方法实现上传
// //参数一Bucket名称 参数二上传到oss文件路径和文件名称 比如 /aa/bb/1.jpg 或者直接使用文件名称 参数三:上传文件的流
// ossClient.putObject(bucketName,fileName,inputStream);
//
// //关闭OSSClient
// ossClient.shutdown();
//
// //把上传之后的文件路径返回
// //需要把上传到阿里云路径返回 https://edu-guli-eric.oss-cn-beijing.aliyuncs.com/1.jpg
// String url = " https://"+bucketName+"."+endpoint+"/"+fileName;
// return url;
// } catch (IOException e) {
// e.printStackTrace();
// return null;
// }
// }
//}

View File

@ -0,0 +1,43 @@
package com.muyu.file.utils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/**
*
*
*
*
*
* @author Eric
* @create 2022-04-24 23:30
*/
@Component
public class ConstantPropertiesUtil implements InitializingBean { //当项目一启动,就会执行该接口的重写方法
@Value("${aliyun.oss.file.endpoint}")
private String endpoint;//地域节点
@Value("${aliyun.oss.file.keyid}")
private String keyId;//id
@Value("${aliyun.oss.file.keysecret}")
private String keySecret;//秘钥
@Value("${aliyun.oss.file.bucketname}")
private String bucketName;//项目名称
public static String END_POINT;
public static String ACCESS_KEY_ID;
public static String ACCESS_KEY_SECRET;
public static String BUCKET_NAME;
@Override
public void afterPropertiesSet() throws Exception {
END_POINT = endpoint;
ACCESS_KEY_ID = keyId;
ACCESS_KEY_SECRET = keySecret;
BUCKET_NAME = bucketName;
}
}

View File

@ -0,0 +1,193 @@
package com.muyu.file.utils;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.comm.Protocol;
import com.aliyun.oss.model.OSSObjectSummary;
import com.aliyun.oss.model.ObjectListing;
import com.muyu.file.config.OSSCloudConfig;
public class OSSCloudClient {
private OSSCloudClient() {
super();
}
private static class SingletonContainer{
private static OSSCloudClient instance = new OSSCloudClient();
}
public static OSSCloudClient getInstance() {
return SingletonContainer.instance;
}
private OSS createOSS() {
ClientBuilderConfiguration conf = new ClientBuilderConfiguration();
// 设置连接OSS所使用的协议HTTP或HTTPS默认为HTTP。
conf.setProtocol(Protocol.HTTPS);
// 创建OSSClient实例。
return new OSSClientBuilder().build(OSSCloudConfig.ENDPOINT, OSSCloudConfig.ACCESSKEYID, OSSCloudConfig.ACCESSKEYSECRET);
}
private Map<String, String> getObjectName(String fileName, String userId) {
Map<String, String> nameMap = new HashMap<>();
OSSCloudConfig config = new OSSCloudConfig();
String format = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
String name = userId + "/" + format + "/" + UUID.randomUUID().toString().replace("-", "") + "_" + fileName;
nameMap.put("objectName", config.getObjectPrefixName() + name);
nameMap.put("filePath", config.getFilePathPrefix() + name);
return nameMap;
}
private String getObjectName(String filePath) {
OSSCloudConfig config = new OSSCloudConfig();
return config.getObjectPrefixName() + filePath.replace(config.getFilePathPrefix(), "");
}
/**
*
* @param fileName
* @param userId id
* @param bytes byte
* @throws Exception
*/
public String uploadFile(String fileName, String userId, byte[] bytes) throws Exception {
Map<String, String> nameMap = this.getObjectName(fileName, userId);
String objectName = nameMap.get("objectName");
OSS ossClient = createOSS();
try {
ossClient.putObject(OSSCloudConfig.BUCKETNAME, objectName, new ByteArrayInputStream(bytes));
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return nameMap.get("filePath");
}
/**
*
* @param fileName
* @param userId id
* @param localPath
* @throws Exception
*/
public String uploadFile(String fileName, String userId, String localPath) throws Exception {
Map<String, String> nameMap = this.getObjectName(fileName, userId);
String objectName = nameMap.get("objectName");
OSS ossClient = createOSS();
try {
ossClient.putObject(OSSCloudConfig.BUCKETNAME, objectName, new FileInputStream(new File(localPath)));
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return nameMap.get("filePath");
}
/**
*
* @param fileName
* @param userId id
* @throws Exception
*/
public String uploadFile(String fileName, String userId, InputStream is) throws Exception {
Map<String, String> nameMap = this.getObjectName(fileName, userId);
String objectName = nameMap.get("objectName");
OSS ossClient = createOSS();
try {
ossClient.putObject(OSSCloudConfig.BUCKETNAME, objectName, is);
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return nameMap.get("filePath");
}
/**
*
* @param filePath 访(https)
* @return
*/
public Boolean fileExist(String filePath) {
String objectName = this.getObjectName(filePath);
OSS ossClient = createOSS();
try {
return ossClient.doesObjectExist(OSSCloudConfig.BUCKETNAME, objectName);
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
/**
*
* @param dirPath 1/20220415
* @return
*/
public List<String> listFiles(String dirPath) {
OSSCloudConfig config = new OSSCloudConfig();
String objectDir = config.getObjectPrefixName() + dirPath;
// String objectName = this.getObjectName(filePath);
OSS ossClient = createOSS();
try {
ObjectListing objectListing = ossClient.listObjects(OSSCloudConfig.BUCKETNAME, objectDir);
List<OSSObjectSummary> sums = objectListing.getObjectSummaries();
List<String> list = new ArrayList<>();
for (OSSObjectSummary s : sums) {
list.add(config.getFilePathPrefix() + (s.getKey().replace(config.getObjectPrefixName(), "")));
}
return list;
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
/**
*
* @param filePath (访)
* @throws Exception
*/
public void deleteFile(String filePath) throws Exception {
String objectName = this.getObjectName(filePath);
OSS ossClient = createOSS();
try {
ossClient.deleteObject(OSSCloudConfig.BUCKETNAME, objectName);
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
public static void main(String[] args) throws Exception {
OSSCloudClient client = OSSCloudClient.getInstance();
String filePath = client.uploadFile("读书记录封面.png", "1", "D:\\Pictures\\bookrecording\\读书记录封面.png");
System.out.println(filePath);
System.out.println(client.fileExist(filePath));
List<String> list = client.listFiles("1/20220416/");
for(String s : list) {
System.out.println(s);
client.deleteFile(s);
}
client.deleteFile("https://zhaohy-bucket.oss-cn-guangzhou.aliyuncs.com/static/images/1/20220415");
}
}

View File

@ -23,3 +23,12 @@ spring:
# 共享配置
shared-configs:
- application-${spring.profiles.active}.${spring.cloud.nacos.config.file-extension}
#阿里云 OSS配置bucket信息
aliyun:
oss:
file:
endpoint: oss-cn-beijing.aliyuncs.com #地域节点
keyid: LTAI5tXLU13zKh4VHzXyz #ID
keysecret: ZgmX5vSqlMF4H5nliXErLxhDQ703HF #秘钥
bucketname: aly-item-eric #项目名称

View File

@ -97,7 +97,7 @@
<select id="selectDbTableList" parameterType="com.muyu.gen.domain.GenTable" resultMap="GenTableResult">
select table_name, table_comment, create_time, update_time from information_schema.tables
where table_schema = (select database())
where (table_schema = (select database()) or table_schema = 'ten-product')
AND table_name NOT LIKE 'qrtz_%' AND table_name NOT LIKE 'gen_%'
AND table_name NOT IN (select table_name from gen_table)
<if test="tableName != null and tableName != ''">