Commit a46dcb87 by 阳浪

minio

parent bcfed5b5
...@@ -124,6 +124,13 @@ ...@@ -124,6 +124,13 @@
<groupId>com.nepxion</groupId> <groupId>com.nepxion</groupId>
<artifactId>discovery-plugin-strategy-starter-service</artifactId> <artifactId>discovery-plugin-strategy-starter-service</artifactId>
</dependency> </dependency>
<!-- 5.minio -->
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>7.0.2</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
package com.yizhi.core.application.file.util;
import com.alibaba.fastjson.JSONObject;
import com.yizhi.core.application.exception.BizException;
import com.yizhi.util.application.constant.ReturnCode;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import sun.misc.BASE64Encoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* 上传工具类
*/
@Component
public class MinioTools {
private Logger logger = LoggerFactory.getLogger(MinioTools.class);
@Autowired
private MinioClient minioClient;
@Value("${spring.minio.switchFlag}")
private String switchFlag;
/**
* 创建桶名
*
* @param bucketName
*/
public void makeBucket(String bucketName){
try {
if(!minioClient.bucketExists(bucketName)){
minioClient.makeBucket(bucketName);
}
} catch (Exception e) {
logger.error("makeBucket异常",e);
}
}
/**
* 功能描述: <br>
* 〈base64上传〉
* @Param: [bucketName, fileName, base64]
* @Return: void
* @Author: yanglang
* @Date: 2023/7/24 10:31
*/
public void uploadImg(String bucketName, String fileName, byte[] base64) {
InputStream in = new ByteArrayInputStream(base64);
uplodFile(bucketName,fileName,in);
}
/**
* 上传文件
*
* @param bucketName 存储桶名
* @param fileName 文件名
* @param in
*/
public void uplodFile(String bucketName, String fileName, InputStream in){
makeBucket(bucketName);
try {
PutObjectOptions options = new PutObjectOptions(in.available(), -1);
minioClient.putObject(bucketName,fileName,in,options);
} catch (Exception e) {
logger.error("存储文件异常", e);
throw new BizException(ReturnCode.BIZ_FAIL.getCode(),"文件存储失败");
}finally {
try {
if(in != null){
in.close();
}
} catch (IOException e) {
logger.error("IO流关闭异常", e);
throw new BizException(ReturnCode.BIZ_FAIL.getCode(),"IO流关闭异常");
}
}
}
/**
* 删除文件
*
* @param bucketName
* @param fileName
* @return
*/
public String deleteFile(String bucketName, String fileName) {
try {
minioClient.removeObject(bucketName, fileName);
} catch (Exception e) {
logger.error("删除文件失败", JSONObject.toJSONString(e));
throw new BizException(ReturnCode.BIZ_FAIL.getCode(),"删除文件失败");
}
return "删除成功";
}
/**
* 获取文件上传路径
*
* @param bucketName
* @param fileName
* @return
*/
public String getFile(String bucketName, String fileName){
String url = "";
try {
// 调用statObject()来判断对象是否存在。
// 如果不存在, statObject()抛出异常,
// 否则则代表对象存在。
minioClient.statObject(bucketName, fileName);
url = minioClient.getObjectUrl(bucketName, fileName);
// 开关控制是否返回全路径给前端
if("on".equalsIgnoreCase(switchFlag)){
url = "/"+ bucketName + url.split(bucketName)[1];
}
} catch (Exception e) {
logger.error("获取文件失败", JSONObject.toJSONString(e));
throw new BizException(ReturnCode.BIZ_FAIL.getCode(),"获取文件失败");
}
return url;
}
/**
* 获取文件
*
* @param bucketName
* @param fileName
* @return
*/
public InputStream getFileInputStream(String bucketName, String fileName){
InputStream in ;
try {
// 调用statObject()来判断对象是否存在。
// 如果不存在, statObject()抛出异常,
// 否则则代表对象存在。
minioClient.statObject(bucketName, fileName);
// 获取"myobject"的输入流。
in = minioClient.getObject(bucketName, fileName);
} catch (Exception e) {
logger.error("获取文件失败", JSONObject.toJSONString(e));
throw new BizException(ReturnCode.BIZ_FAIL.getCode(),"获取文件失败");
}
return in;
}
public String getFileBase64Str(String bucketName, String fileName) throws IOException {
InputStream in = null;
try {
// 调用statObject()来判断对象是否存在。
// 如果不存在, statObject()抛出异常,
// 否则则代表对象存在。
minioClient.statObject(bucketName, fileName);
// 获取"myobject"的输入流。
in = minioClient.getObject(bucketName, fileName);
byte[] b = null;
byte[] buff = new byte[1024];
ByteArrayOutputStream output = new ByteArrayOutputStream();
int n = 0;
while (-1 != (n = in.read(buff)) ){
output.write(buff, 0, n);
}
b = output.toByteArray();
// 对字节数组Base64编码
BASE64Encoder encoder = new BASE64Encoder();
// 返回 Base64 编码过的字节数组字符串
return encoder.encode(b);
} catch (Exception e) {
logger.error("获取文件失败", JSONObject.toJSONString(e));
throw new BizException(ReturnCode.BIZ_FAIL.getCode(),"获取文件失败");
}finally {
if(in!=null){
in.close();
}
}
}
public String getFileStr(String bucketName, String fileName) throws IOException {
InputStream in = null;
try {
// 调用statObject()来判断对象是否存在。
// 如果不存在, statObject()抛出异常,
// 否则则代表对象存在。
minioClient.statObject(bucketName, fileName);
// 获取"myobject"的输入流。
in = minioClient.getObject(bucketName, fileName);
byte[] b = null;
byte[] buff = new byte[1024];
ByteArrayOutputStream output = new ByteArrayOutputStream();
int n = 0;
while (-1 != (n = in.read(buff)) ){
output.write(buff, 0, n);
}
b = output.toByteArray();
return new String(b, "UTF-8");
} catch (Exception e) {
logger.error("获取文件失败", JSONObject.toJSONString(e));
throw new BizException(ReturnCode.BIZ_FAIL.getCode(),"获取文件失败");
}finally {
if(in!=null){
in.close();
}
}
}
}
package com.yizhi.core.application.file.util; package com.yizhi.core.application.file.util;
import com.aliyun.oss.ClientConfiguration; import com.yizhi.util.application.spring.SpringUtil;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.CompleteMultipartUploadResult;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyun.oss.model.UploadFileRequest;
import com.aliyun.oss.model.UploadFileResult;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
import java.util.Calendar; import java.io.FileInputStream;
/** /**
* @author wenjunlong * @author wenjunlong
*/ */
public class OssUpload { public class OssUpload {
private static String endpoint = "https://oss-cn-shanghai.aliyuncs.com"; private static String bucketName = "upload";
private static String accessKeyId = "LTAI5tL1VySRnwAKhTxXfsAG";
private static String accessKeySecret = "ajcWkXhbKZBDoRnQdgfQGAAlVZZXMs";
private static String bucketName = "fulan-edu";
private static String proxyUsername = null; //代理用户
private static String proxyPassword = null; //代理密码
private static final Logger LOGGER = LoggerFactory.getLogger(OssUpload.class);
/** /**
* 上传文件到阿里云 * 上传文件到阿里云
...@@ -48,54 +31,14 @@ public class OssUpload { ...@@ -48,54 +31,14 @@ public class OssUpload {
* @return * @return
*/ */
public static String upload(String uploadFile, String key, String proxyUrl, Integer proxyPort) { public static String upload(String uploadFile, String key, String proxyUrl, Integer proxyPort) {
OSSClient ossClient = null; MinioTools minioTools = SpringUtil.getBean(MinioTools.class);
if (!StringUtils.isBlank(proxyUrl) && proxyPort != null && proxyPort != 0) {
LOGGER.info("创建OSSClient代理连接:IP={}, PORT={}", proxyUrl, proxyPort);
ClientConfiguration config = new ClientConfiguration();
config.setProxyHost(proxyUrl);
config.setProxyPort(proxyPort);
config.setProxyPassword(proxyPassword);
config.setProxyUsername(proxyUsername);
ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret, config);
} else {
LOGGER.info("创建OSSClient正常连接");
ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
}
try { try {
UploadFileRequest uploadFileRequest = new UploadFileRequest(bucketName, key); minioTools.uplodFile(bucketName,key,new FileInputStream(uploadFile));
// 待上传的本地文件 return minioTools.getFile(bucketName,key);
uploadFileRequest.setUploadFile(uploadFile); } catch (Exception oe) {
// 设置并发下载数,默认1
uploadFileRequest.setTaskNum(5);
// 设置分片大小,默认100KB
uploadFileRequest.setPartSize(1024 * 1024 * 1);
// 开启断点续传,默认关闭
uploadFileRequest.setEnableCheckpoint(true);
UploadFileResult uploadResult = ossClient.uploadFile(uploadFileRequest);
CompleteMultipartUploadResult multipartUploadResult =
uploadResult.getMultipartUploadResult();
System.out.println(multipartUploadResult.getLocation());
return multipartUploadResult.getLocation();
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message: " + oe.getErrorCode());
System.out.println("Error Code: " + oe.getErrorCode());
System.out.println("Request ID: " + oe.getRequestId());
System.out.println("Host ID: " + oe.getHostId());
return "error";
} catch (Throwable e) {
e.printStackTrace();
return "error"; return "error";
} finally {
ossClient.shutdown();
} }
} }
/** /**
...@@ -107,36 +50,13 @@ public class OssUpload { ...@@ -107,36 +50,13 @@ public class OssUpload {
*/ */
public static String upload(byte[] data, String filename) { public static String upload(byte[] data, String filename) {
String ret = ""; String ret = "";
OSSClient ossClient = null; MinioTools minioTools = SpringUtil.getBean(MinioTools.class);
try { try {
ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); minioTools.uplodFile(bucketName,filename,new ByteArrayInputStream(data));
PutObjectResult result = ossClient.putObject(bucketName, filename, new ByteArrayInputStream(data)); ret = minioTools.getFile(bucketName,filename);
ret = result.getRequestId(); } catch (Exception e) {
} catch (OSSException e) {
ret = e.getMessage();
} catch (com.aliyun.oss.ClientException e) {
ret = e.getMessage(); ret = e.getMessage();
} }
// 关闭OSSClient。
ossClient.shutdown();
// 设置URL过期时间为1小时。
Calendar cal = Calendar.getInstance();
cal.add(Calendar.YEAR, 2);//增加一年
//cal.add(Calendar.DATE, n);//增加一天
//cal.add(Calendar.DATE, -10);//减10天
//cal.add(Calendar.MONTH, 1);//增加一个月
//Date expiration = new Date(System.currentTimeMillis() + (1000 * 24*3600 * 1000));
ret = ossClient.generatePresignedUrl(bucketName, filename, cal.getTime()).toString();
return ret; return ret;
} }
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(OssUpload.upload("D:\\importpath\\org_import_template.xlsx", "org_import_template.xlsx"));
}
});
thread.start();
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment