first commit

This commit is contained in:
2024-04-01 10:35:09 +08:00
parent 830967b85a
commit 117e379d6b
2337 changed files with 1632 additions and 323680 deletions
+3 -9
View File
@@ -1,10 +1,4 @@
## ide
**/.idea
/target/
/.idea/
*.iml
## backend
**/target
**/logs
## front
**/*.lock
rebel.xml
View File
View File
@@ -1,272 +1,272 @@
package com.jero.common.util;
import java.io.*;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.sql.DataSource;
import cn.afterturn.easypoi.util.PoiPublicUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.jero.common.constant.CommonConstant;
import com.jero.common.constant.DataBaseConstant;
import com.jero.common.exception.JeroBootException;
import com.jero.common.util.filter.FileTypeFilter;
import com.jero.common.util.oss.OssBootUtil;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.toolkit.JdbcUtils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class CommonUtils {
private CommonUtils(){
}
//中文正则
private static Pattern ZHONGWEN_PATTERN = Pattern.compile("[\u4e00-\u9fa5]");
public static String uploadOnlineImage(byte[] data,String basePath,String bizPath,String uploadType){
String dbPath = null;
String fileName = "image" + Math.round(Math.random() * 100000000000L);
fileName += "." + PoiPublicUtil.getFileExtendName(data);
try {
if(CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)){
File file = new File(basePath + File.separator + bizPath + File.separator );
if (!file.exists()) {
file.mkdirs();// 创建文件根目录
}
String savePath = file.getPath() + File.separator + fileName;
File savefile = new File(savePath);
FileCopyUtils.copy(data, savefile);
dbPath = bizPath + File.separator + fileName;
}else {
InputStream in = new ByteArrayInputStream(data);
String relativePath = bizPath+ File.separator +fileName;
if(CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)){
dbPath = MinioUtil.upload(in,relativePath);
}else if(CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)){
dbPath = OssBootUtil.upload(in,relativePath);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return dbPath;
}
/**
* 判断文件名是否带盘符重新处理
* @param fileName
* @return
*/
public static String getFileName(String fileName){
//判断是否带有盘符信息
// Check for Unix-style path
int unixSep = fileName.lastIndexOf('/');
// Check for Windows-style path
int winSep = fileName.lastIndexOf('\\');
// Cut off at latest possible point
int pos = (winSep > unixSep ? winSep : unixSep);
if (pos != -1) {
// Any sort of path separator found...
fileName = fileName.substring(pos + 1);
}
//替换上传文件名字的特殊字符
fileName = fileName.replace("=","").replace(",","").replace("&","")
.replace("#", "").replace("", "").replace("", "");
//替换上传文件名字中的空格
fileName=fileName.replaceAll("\\s","");
return fileName;
}
// java 判断字符串里是否包含中文字符
public static boolean ifContainChinese(String str) {
if(str.getBytes().length == str.length()){
return false;
}else{
Matcher m = ZHONGWEN_PATTERN.matcher(str);
return m.find();
}
}
/**
* 统一全局上传
* @Return: java.lang.String
*/
public static String upload(MultipartFile file, String bizPath, String uploadType) {
String url = "";
if(CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)){
url = MinioUtil.upload(file,bizPath);
}else{
url = OssBootUtil.upload(file,bizPath);
}
return url;
}
/**
* 统一全局上传 带桶
* @Return: java.lang.String
*/
public static String upload(MultipartFile file, String bizPath, String uploadType, String customBucket) {
String url = "";
if(CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)){
url = MinioUtil.upload(file,bizPath,customBucket);
}else{
url = OssBootUtil.upload(file,bizPath,customBucket);
}
return url;
}
/**
* 本地文件上传
* @param mf 文件
* @param bizPath 自定义路径
* @return
*/
public static String uploadLocal(MultipartFile mf,String bizPath, String uploadpath){
try {
//update-begin-author:liusq date:20210809 for: 过滤上传文件类型
FileTypeFilter.fileTypeFilter(mf);
//update-end-author:liusq date:20210809 for: 过滤上传文件类型
String ctxPath = uploadpath;
String fileName = null;
File file = new File(ctxPath + File.separator + bizPath + File.separator );
if (!file.exists()) {
file.mkdirs();// 创建文件根目录
}
String orgName = mf.getOriginalFilename();// 获取文件名
orgName = CommonUtils.getFileName(orgName);
if(orgName.indexOf(".")!=-1){
fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."));
}else{
fileName = orgName+ "_" + System.currentTimeMillis();
}
String savePath = file.getPath() + File.separator + fileName;
File savefile = new File(savePath);
FileCopyUtils.copy(mf.getBytes(), savefile);
String dbpath = null;
if(oConvertUtils.isNotEmpty(bizPath)){
dbpath = bizPath + File.separator + fileName;
}else{
dbpath = fileName;
}
if (dbpath.contains("\\")) {
dbpath = dbpath.replace("\\", "/");
}
return dbpath;
} catch (IOException e) {
log.error(e.getMessage(), e);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return "";
}
/** 当前系统数据库类型 */
private static String DB_TYPE = "";
private static DbType dbTypeEnum = null;
/**
* 全局获取平台数据库类型作废了
* @deprecated 不推荐
* @return
*/
@Deprecated
public static String getDatabaseType() {
if(oConvertUtils.isNotEmpty(DB_TYPE)){
return DB_TYPE;
}
DataSource dataSource = SpringContextUtils.getApplicationContext().getBean(DataSource.class);
try {
return getDatabaseTypeByDataSource(dataSource);
} catch (SQLException e) {
log.warn(e.getMessage(), e);
return "";
}
}
/**
* 全局获取平台数据库类型对应mybaisPlus枚举
* @return
*/
public static DbType getDatabaseTypeEnum() {
if (oConvertUtils.isNotEmpty(dbTypeEnum)) {
return dbTypeEnum;
}
DataSource dataSource = SpringContextUtils.getApplicationContext().getBean(DataSource.class);
try (Connection connection = dataSource.getConnection();) {
dbTypeEnum = JdbcUtils.getDbType(connection.getMetaData().getURL());
return dbTypeEnum;
} catch (SQLException e) {
log.warn(e.getMessage(), e);
return null;
}
}
/**
* 获取数据库类型
* @param dataSource
* @return
* @throws SQLException
*/
private static String getDatabaseTypeByDataSource(DataSource dataSource) throws SQLException{
if("".equals(DB_TYPE)) {
Connection connection = dataSource.getConnection();
try {
DatabaseMetaData md = connection.getMetaData();
String dbType = md.getDatabaseProductName().toLowerCase();
if(dbType.indexOf("mysql")>=0) {
DB_TYPE = DataBaseConstant.DB_TYPE_MYSQL;
}else if(dbType.indexOf("oracle")>=0 ||dbType.indexOf("dm")>=0) {
DB_TYPE = DataBaseConstant.DB_TYPE_ORACLE;
}else if(dbType.indexOf("sqlserver")>=0||dbType.indexOf("sql server")>=0) {
DB_TYPE = DataBaseConstant.DB_TYPE_SQLSERVER;
}else if(dbType.indexOf("postgresql")>=0) {
DB_TYPE = DataBaseConstant.DB_TYPE_POSTGRESQL;
}else {
throw new JeroBootException("数据库类型:["+dbType+"]不识别!");
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}finally {
connection.close();
}
}
return DB_TYPE;
}
/**
* 黑名单限制文件
* @date 2021/4/14 6:18
* @param fileName 文件名
* @return boolean true处于黑名单 false不处于黑名单
*/
public static boolean limitFileSuffix(String fileName,String[] fileSuffixLimits){
final List<String> fileNameList = Arrays.asList(fileSuffixLimits);
boolean isExists = fileNameList.stream().anyMatch(name -> fileName.substring(0,fileName.lastIndexOf('.')).contains(name)||fileName.substring(fileName.lastIndexOf('.')).contains(name));
return isExists;
}
/**
* RSA 使用私钥解密
* @date 2021/4/15 16:11
* @param str 待解密的字符串
* @param RSAPrivateKey 私钥
* @return String 解密后的字符串
*/
public static String decryptBtRsaPriKey(String str,String RSAPrivateKey){
RSA rsa = new RSA(RSAPrivateKey, null);
byte[] decrypt = rsa.decrypt(str, KeyType.PrivateKey);
return new String(decrypt);
}
}
package com.jero.common.util;
import java.io.*;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.sql.DataSource;
import cn.afterturn.easypoi.util.PoiPublicUtil;
import cn.hutool.crypto.asymmetric.KeyType;
import cn.hutool.crypto.asymmetric.RSA;
import com.jero.common.constant.CommonConstant;
import com.jero.common.constant.DataBaseConstant;
import com.jero.common.exception.JeroBootException;
import com.jero.common.util.filter.FileTypeFilter;
import com.jero.common.util.oss.OssBootUtil;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.multipart.MultipartFile;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.toolkit.JdbcUtils;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class CommonUtils {
private CommonUtils(){
}
//中文正则
private static Pattern ZHONGWEN_PATTERN = Pattern.compile("[\u4e00-\u9fa5]");
public static String uploadOnlineImage(byte[] data,String basePath,String bizPath,String uploadType){
String dbPath = null;
String fileName = "image" + Math.round(Math.random() * 100000000000L);
fileName += "." + PoiPublicUtil.getFileExtendName(data);
try {
if(CommonConstant.UPLOAD_TYPE_LOCAL.equals(uploadType)){
File file = new File(basePath + File.separator + bizPath + File.separator );
if (!file.exists()) {
file.mkdirs();// 创建文件根目录
}
String savePath = file.getPath() + File.separator + fileName;
File savefile = new File(savePath);
FileCopyUtils.copy(data, savefile);
dbPath = bizPath + File.separator + fileName;
}else {
InputStream in = new ByteArrayInputStream(data);
String relativePath = bizPath+ File.separator +fileName;
if(CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)){
dbPath = MinioUtil.upload(in,relativePath);
}else if(CommonConstant.UPLOAD_TYPE_OSS.equals(uploadType)){
dbPath = OssBootUtil.upload(in,relativePath);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return dbPath;
}
/**
* 判断文件名是否带盘符重新处理
* @param fileName
* @return
*/
public static String getFileName(String fileName){
//判断是否带有盘符信息
// Check for Unix-style path
int unixSep = fileName.lastIndexOf('/');
// Check for Windows-style path
int winSep = fileName.lastIndexOf('\\');
// Cut off at latest possible point
int pos = (winSep > unixSep ? winSep : unixSep);
if (pos != -1) {
// Any sort of path separator found...
fileName = fileName.substring(pos + 1);
}
//替换上传文件名字的特殊字符
fileName = fileName.replace("=","").replace(",","").replace("&","")
.replace("#", "").replace("", "").replace("", "");
//替换上传文件名字中的空格
fileName=fileName.replaceAll("\\s","");
return fileName;
}
// java 判断字符串里是否包含中文字符
public static boolean ifContainChinese(String str) {
if(str.getBytes().length == str.length()){
return false;
}else{
Matcher m = ZHONGWEN_PATTERN.matcher(str);
return m.find();
}
}
/**
* 统一全局上传
* @Return: java.lang.String
*/
public static String upload(MultipartFile file, String bizPath, String uploadType) {
String url = "";
if(CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)){
url = MinioUtil.upload(file,bizPath);
}else{
url = OssBootUtil.upload(file,bizPath);
}
return url;
}
/**
* 统一全局上传 带桶
* @Return: java.lang.String
*/
public static String upload(MultipartFile file, String bizPath, String uploadType, String customBucket) {
String url = "";
if(CommonConstant.UPLOAD_TYPE_MINIO.equals(uploadType)){
url = MinioUtil.upload(file,bizPath,customBucket);
}else{
url = OssBootUtil.upload(file,bizPath,customBucket);
}
return url;
}
/**
* 本地文件上传
* @param mf 文件
* @param bizPath 自定义路径
* @return
*/
public static String uploadLocal(MultipartFile mf,String bizPath, String uploadpath){
try {
//update-begin-author:liusq date:20210809 for: 过滤上传文件类型
FileTypeFilter.fileTypeFilter(mf);
//update-end-author:liusq date:20210809 for: 过滤上传文件类型
String ctxPath = uploadpath;
String fileName = null;
File file = new File(ctxPath + File.separator + bizPath + File.separator );
if (!file.exists()) {
file.mkdirs();// 创建文件根目录
}
String orgName = mf.getOriginalFilename();// 获取文件名
orgName = CommonUtils.getFileName(orgName);
if(orgName.indexOf(".")!=-1){
fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."));
}else{
fileName = orgName+ "_" + System.currentTimeMillis();
}
String savePath = file.getPath() + File.separator + fileName;
File savefile = new File(savePath);
FileCopyUtils.copy(mf.getBytes(), savefile);
String dbpath = null;
if(oConvertUtils.isNotEmpty(bizPath)){
dbpath = bizPath + File.separator + fileName;
}else{
dbpath = fileName;
}
if (dbpath.contains("\\")) {
dbpath = dbpath.replace("\\", "/");
}
return dbpath;
} catch (IOException e) {
log.error(e.getMessage(), e);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return "";
}
/** 当前系统数据库类型 */
private static String DB_TYPE = "";
private static DbType dbTypeEnum = null;
/**
* 全局获取平台数据库类型作废了
* @deprecated 不推荐
* @return
*/
@Deprecated
public static String getDatabaseType() {
if(oConvertUtils.isNotEmpty(DB_TYPE)){
return DB_TYPE;
}
DataSource dataSource = SpringContextUtils.getApplicationContext().getBean(DataSource.class);
try {
return getDatabaseTypeByDataSource(dataSource);
} catch (SQLException e) {
log.warn(e.getMessage(), e);
return "";
}
}
/**
* 全局获取平台数据库类型对应mybaisPlus枚举
* @return
*/
public static DbType getDatabaseTypeEnum() {
if (oConvertUtils.isNotEmpty(dbTypeEnum)) {
return dbTypeEnum;
}
DataSource dataSource = SpringContextUtils.getApplicationContext().getBean(DataSource.class);
try (Connection connection = dataSource.getConnection();) {
dbTypeEnum = JdbcUtils.getDbType(connection.getMetaData().getURL());
return dbTypeEnum;
} catch (SQLException e) {
log.warn(e.getMessage(), e);
return null;
}
}
/**
* 获取数据库类型
* @param dataSource
* @return
* @throws SQLException
*/
private static String getDatabaseTypeByDataSource(DataSource dataSource) throws SQLException{
if("".equals(DB_TYPE)) {
Connection connection = dataSource.getConnection();
try {
DatabaseMetaData md = connection.getMetaData();
String dbType = md.getDatabaseProductName().toLowerCase();
if(dbType.indexOf("mysql")>=0) {
DB_TYPE = DataBaseConstant.DB_TYPE_MYSQL;
}else if(dbType.indexOf("oracle")>=0 ||dbType.indexOf("dm")>=0) {
DB_TYPE = DataBaseConstant.DB_TYPE_ORACLE;
}else if(dbType.indexOf("sqlserver")>=0||dbType.indexOf("sql server")>=0) {
DB_TYPE = DataBaseConstant.DB_TYPE_SQLSERVER;
}else if(dbType.indexOf("postgresql")>=0) {
DB_TYPE = DataBaseConstant.DB_TYPE_POSTGRESQL;
}else {
throw new JeroBootException("数据库类型:["+dbType+"]不识别!");
}
} catch (Exception e) {
log.error(e.getMessage(), e);
}finally {
connection.close();
}
}
return DB_TYPE;
}
/**
* 黑名单限制文件
* @date 2021/4/14 6:18
* @param fileName 文件名
* @return boolean true处于黑名单 false不处于黑名单
*/
public static boolean limitFileSuffix(String fileName,String[] fileSuffixLimits){
final List<String> fileNameList = Arrays.asList(fileSuffixLimits);
boolean isExists = fileNameList.stream().anyMatch(name -> fileName.substring(0,fileName.lastIndexOf('.')).contains(name)||fileName.substring(fileName.lastIndexOf('.')).contains(name));
return isExists;
}
/**
* RSA 使用私钥解密
* @date 2021/4/15 16:11
* @param str 待解密的字符串
* @param RSAPrivateKey 私钥
* @return String 解密后的字符串
*/
public static String decryptBtRsaPriKey(String str,String RSAPrivateKey){
RSA rsa = new RSA(RSAPrivateKey, null);
byte[] decrypt = rsa.decrypt(str, KeyType.PrivateKey);
return new String(decrypt);
}
}
@@ -1,224 +1,224 @@
package com.jero.common.util;
import com.jero.common.util.filter.FileTypeFilter;
import com.jero.common.util.filter.StrAttackFilter;
import io.minio.*;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
/**
* minio文件上传工具类
*/
@Slf4j
public class MinioUtil {
private MinioUtil(){
}
private static String minioUrl;
private static String minioName;
private static String minioPass;
private static String bucketName;
public static void setMinioUrl(String minioUrl) {
MinioUtil.minioUrl = minioUrl;
}
public static void setMinioName(String minioName) {
MinioUtil.minioName = minioName;
}
public static void setMinioPass(String minioPass) {
MinioUtil.minioPass = minioPass;
}
public static void setBucketName(String bucketName) {
MinioUtil.bucketName = bucketName;
}
public static String getMinioUrl() {
return minioUrl;
}
public static String getBucketName() {
return bucketName;
}
private static MinioClient minioClient = null;
/**
* 上传文件
* @param file
* @return
*/
public static String upload(MultipartFile file, String bizPath, String customBucket) {
String fileUrl = "";
//update-begin-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符防止攻击
bizPath=StrAttackFilter.filter(bizPath);
//update-end-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符防止攻击
String newBucket = bucketName;
if(oConvertUtils.isNotEmpty(customBucket)){
newBucket = customBucket;
}
try {
initMinio(minioUrl, minioName,minioPass);
// 检查存储桶是否已经存在
if(minioClient.bucketExists(BucketExistsArgs.builder().bucket(newBucket).build())) {
log.info("Bucket already exists.");
} else {
// 创建一个名为ota的存储桶
minioClient.makeBucket(MakeBucketArgs.builder().bucket(newBucket).build());
log.info("create a new bucket.");
}
//update-begin-author:liusq date:20210809 for: 过滤上传文件类型
FileTypeFilter.fileTypeFilter(file);
//update-end-author:liusq date:20210809 for: 过滤上传文件类型
InputStream stream = file.getInputStream();
// 获取文件名
String orgName = file.getOriginalFilename();
if("".equals(orgName)){
orgName=file.getName();
}
orgName = CommonUtils.getFileName(orgName);
String objectName = bizPath+File.separator
+(!orgName.contains(".")
?orgName + "_" + System.currentTimeMillis()
:orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."))
);
// 使用putObject上传一个本地文件到存储桶中
if(objectName.startsWith("/")){
objectName = objectName.substring(1);
}
PutObjectArgs objectArgs = PutObjectArgs.builder().object(objectName)
.bucket(newBucket)
.contentType("application/octet-stream")
.stream(stream,stream.available(),-1).build();
minioClient.putObject(objectArgs);
stream.close();
fileUrl = minioUrl+newBucket+ File.separator +objectName;
}catch (Exception e){
log.error(e.getMessage(), e);
}
return fileUrl;
}
/**
* 文件上传
* @param file
* @param bizPath
* @return
*/
public static String upload(MultipartFile file, String bizPath) {
return upload(file,bizPath,null);
}
/**
* 获取文件流
* @param bucketName
* @param objectName
* @return
*/
public static InputStream getMinioFile(String bucketName, String objectName){
InputStream inputStream = null;
try {
initMinio(minioUrl, minioName, minioPass);
GetObjectArgs objectArgs = GetObjectArgs.builder().object(objectName)
.bucket(bucketName).build();
inputStream = minioClient.getObject(objectArgs);
} catch (Exception e) {
log.info("文件获取失败" + e.getMessage());
}
return inputStream;
}
/**
* 删除文件
* @param bucketName
* @param objectName
* @throws Exception
*/
public static void removeObject(String bucketName, String objectName) {
try {
initMinio(minioUrl, minioName,minioPass);
RemoveObjectArgs objectArgs = RemoveObjectArgs.builder().object(objectName)
.bucket(bucketName).build();
minioClient.removeObject(objectArgs);
}catch (Exception e){
log.info("文件删除失败" + e.getMessage());
}
}
/**
* 获取文件外链
* @param bucketName
* @param objectName
* @param expires
* @return
*/
public static String getObjectURL(String bucketName, String objectName, Integer expires) {
initMinio(minioUrl, minioName,minioPass);
try{
GetPresignedObjectUrlArgs objectArgs = GetPresignedObjectUrlArgs.builder().object(objectName)
.bucket(bucketName)
.expiry(expires).build();
String url = minioClient.getPresignedObjectUrl(objectArgs);
return URLDecoder.decode(url,"UTF-8");
}catch (Exception e){
log.info("文件路径获取失败" + e.getMessage());
}
return null;
}
/**
* 初始化客户端
* @param minioUrl
* @param minioName
* @param minioPass
* @return
*/
private static MinioClient initMinio(String minioUrl, String minioName,String minioPass) {
if (minioClient == null) {
try {
minioClient = MinioClient.builder()
.endpoint(minioUrl)
.credentials(minioName, minioPass)
.build();
} catch (Exception e) {
e.printStackTrace();
}
}
return minioClient;
}
/**
* 上传文件到minio
* @param stream
* @param relativePath
* @return
*/
public static String upload(InputStream stream,String relativePath) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException {
initMinio(minioUrl, minioName,minioPass);
if(minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
log.info("Bucket already exists.");
} else {
// 创建一个名为ota的存储桶
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
log.info("create a new bucket.");
}
PutObjectArgs objectArgs = PutObjectArgs.builder().object(relativePath)
.bucket(bucketName)
.contentType("application/octet-stream")
.stream(stream,stream.available(),-1).build();
minioClient.putObject(objectArgs);
stream.close();
return minioUrl+bucketName+"/"+relativePath;
}
}
package com.jero.common.util;
import com.jero.common.util.filter.FileTypeFilter;
import com.jero.common.util.filter.StrAttackFilter;
import io.minio.*;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
/**
* minio文件上传工具类
*/
@Slf4j
public class MinioUtil {
private MinioUtil(){
}
private static String minioUrl;
private static String minioName;
private static String minioPass;
private static String bucketName;
public static void setMinioUrl(String minioUrl) {
MinioUtil.minioUrl = minioUrl;
}
public static void setMinioName(String minioName) {
MinioUtil.minioName = minioName;
}
public static void setMinioPass(String minioPass) {
MinioUtil.minioPass = minioPass;
}
public static void setBucketName(String bucketName) {
MinioUtil.bucketName = bucketName;
}
public static String getMinioUrl() {
return minioUrl;
}
public static String getBucketName() {
return bucketName;
}
private static MinioClient minioClient = null;
/**
* 上传文件
* @param file
* @return
*/
public static String upload(MultipartFile file, String bizPath, String customBucket) {
String fileUrl = "";
//update-begin-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符防止攻击
bizPath=StrAttackFilter.filter(bizPath);
//update-end-author:wangshuai date:20201012 for: 过滤上传文件夹名特殊字符防止攻击
String newBucket = bucketName;
if(oConvertUtils.isNotEmpty(customBucket)){
newBucket = customBucket;
}
try {
initMinio(minioUrl, minioName,minioPass);
// 检查存储桶是否已经存在
if(minioClient.bucketExists(BucketExistsArgs.builder().bucket(newBucket).build())) {
log.info("Bucket already exists.");
} else {
// 创建一个名为ota的存储桶
minioClient.makeBucket(MakeBucketArgs.builder().bucket(newBucket).build());
log.info("create a new bucket.");
}
//update-begin-author:liusq date:20210809 for: 过滤上传文件类型
FileTypeFilter.fileTypeFilter(file);
//update-end-author:liusq date:20210809 for: 过滤上传文件类型
InputStream stream = file.getInputStream();
// 获取文件名
String orgName = file.getOriginalFilename();
if("".equals(orgName)){
orgName=file.getName();
}
orgName = CommonUtils.getFileName(orgName);
String objectName = bizPath+File.separator
+(!orgName.contains(".")
?orgName + "_" + System.currentTimeMillis()
:orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.lastIndexOf("."))
);
// 使用putObject上传一个本地文件到存储桶中
if(objectName.startsWith("/")){
objectName = objectName.substring(1);
}
PutObjectArgs objectArgs = PutObjectArgs.builder().object(objectName)
.bucket(newBucket)
.contentType("application/octet-stream")
.stream(stream,stream.available(),-1).build();
minioClient.putObject(objectArgs);
stream.close();
fileUrl = minioUrl+newBucket+ File.separator +objectName;
}catch (Exception e){
log.error(e.getMessage(), e);
}
return fileUrl;
}
/**
* 文件上传
* @param file
* @param bizPath
* @return
*/
public static String upload(MultipartFile file, String bizPath) {
return upload(file,bizPath,null);
}
/**
* 获取文件流
* @param bucketName
* @param objectName
* @return
*/
public static InputStream getMinioFile(String bucketName, String objectName){
InputStream inputStream = null;
try {
initMinio(minioUrl, minioName, minioPass);
GetObjectArgs objectArgs = GetObjectArgs.builder().object(objectName)
.bucket(bucketName).build();
inputStream = minioClient.getObject(objectArgs);
} catch (Exception e) {
log.info("文件获取失败" + e.getMessage());
}
return inputStream;
}
/**
* 删除文件
* @param bucketName
* @param objectName
* @throws Exception
*/
public static void removeObject(String bucketName, String objectName) {
try {
initMinio(minioUrl, minioName,minioPass);
RemoveObjectArgs objectArgs = RemoveObjectArgs.builder().object(objectName)
.bucket(bucketName).build();
minioClient.removeObject(objectArgs);
}catch (Exception e){
log.info("文件删除失败" + e.getMessage());
}
}
/**
* 获取文件外链
* @param bucketName
* @param objectName
* @param expires
* @return
*/
public static String getObjectURL(String bucketName, String objectName, Integer expires) {
initMinio(minioUrl, minioName,minioPass);
try{
GetPresignedObjectUrlArgs objectArgs = GetPresignedObjectUrlArgs.builder().object(objectName)
.bucket(bucketName)
.expiry(expires).build();
String url = minioClient.getPresignedObjectUrl(objectArgs);
return URLDecoder.decode(url,"UTF-8");
}catch (Exception e){
log.info("文件路径获取失败" + e.getMessage());
}
return null;
}
/**
* 初始化客户端
* @param minioUrl
* @param minioName
* @param minioPass
* @return
*/
private static MinioClient initMinio(String minioUrl, String minioName,String minioPass) {
if (minioClient == null) {
try {
minioClient = MinioClient.builder()
.endpoint(minioUrl)
.credentials(minioName, minioPass)
.build();
} catch (Exception e) {
e.printStackTrace();
}
}
return minioClient;
}
/**
* 上传文件到minio
* @param stream
* @param relativePath
* @return
*/
public static String upload(InputStream stream,String relativePath) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, ErrorResponseException {
initMinio(minioUrl, minioName,minioPass);
if(minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())) {
log.info("Bucket already exists.");
} else {
// 创建一个名为ota的存储桶
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
log.info("create a new bucket.");
}
PutObjectArgs objectArgs = PutObjectArgs.builder().object(relativePath)
.bucket(bucketName)
.contentType("application/octet-stream")
.stream(stream,stream.available(),-1).build();
minioClient.putObject(objectArgs);
stream.close();
return minioUrl+bucketName+"/"+relativePath;
}
}

Some files were not shown because too many files have changed in this diff Show More