com.github.javaclub.ossclient.impl.MinioOssClient Maven / Gradle / Ivy
The newest version!
package com.github.javaclub.ossclient.impl;
import java.io.ByteArrayInputStream;
import java.util.Date;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.web.multipart.MultipartFile;
import com.github.javaclub.BizException;
import com.github.javaclub.Constants.MemCapacity;
import com.github.javaclub.delaytask.DelayQueueProducer;
import com.github.javaclub.ossclient.OssClient;
import com.github.javaclub.ossclient.OssConstants;
import com.github.javaclub.ossclient.OssConstants.Minio;
import com.github.javaclub.ossclient.confg.MinioConfig;
import com.github.javaclub.ossclient.util.AssetsUtils;
import com.github.javaclub.toolbox.ToolBox.Files;
import com.github.javaclub.toolbox.ToolBox.Objects;
import com.github.javaclub.toolbox.ToolBox.Strings;
import com.github.javaclub.toolbox.ToolBox.UUID;
import com.github.javaclub.toolbox.conf.CompositeAppConfigProperties;
import com.github.javaclub.toolbox.spring.BeanFactory;
import com.github.javaclub.toolbox.utils.ThreadLocalDateFormatter;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
public class MinioOssClient implements OssClient, InitializingBean {
static final Logger log = LoggerFactory.getLogger(MinioOssClient.class);
private String endpoint;
private String accessKey;
private String secretKey;
private String cdnDomain;
private String cdnProtocol;
private String defaultBucket;
private int fileUploadLimitMbSize; // 限制上限为 {xx} MB
private boolean doOriginReferCheck;
private boolean fileArchivedByDate;
@Override
public void afterPropertiesSet() throws Exception {
endpoint = CompositeAppConfigProperties.getInstance().getValue(Minio.ENDPOINT);
accessKey = CompositeAppConfigProperties.getInstance().getValue(Minio.ACCESS_KEY);
secretKey = CompositeAppConfigProperties.getInstance().getValue(Minio.SECRET_KEY);
cdnDomain = CompositeAppConfigProperties.getInstance().getValue(Minio.CDN_DOMAIN);
cdnProtocol = CompositeAppConfigProperties.getInstance().getValue(Minio.CDN_PROTOCOL);
defaultBucket = CompositeAppConfigProperties.getInstance().getValue(Minio.DEFAULT_BUCKET);
fileUploadLimitMbSize = CompositeAppConfigProperties.getInstance().intValue(OssConstants.FILE_UPLOAD_LIMIT_SIZE, 10);
doOriginReferCheck = CompositeAppConfigProperties.getInstance().boolValue(OssConstants.SAME_ORIGIN_CHECK, true);
fileArchivedByDate = CompositeAppConfigProperties.getInstance().boolValue(OssConstants.FILE_ARCHIVED_BY_DATE, true);
String[] array = new String[] {
endpoint, accessKey, secretKey, cdnDomain, cdnProtocol
};
Objects.requireTrue(Strings.areNotBlank(array), "Minio Oss 配置参数缺失!");
}
@Override
public String upload(MultipartFile file, String relativePathInBucket, Map params) {
MinioClient minioClient = MinioConfig.getInstance();
if (null == minioClient) {
throw new BizException("MinioClient 尚未初始化!");
}
String bucketVar = (String) params.getOrDefault(OssConstants.BUCKET_NAME_PARAM_KEY, Strings.EMPTY);
String thisUploadBucket = Strings.isBlank(bucketVar) ? defaultBucket : bucketVar;
String objectPath = Strings.endsWithIgnoreCase(relativePathInBucket, "/") ? relativePathInBucket
: Strings.concat(relativePathInBucket, "/");
if (fileArchivedByDate) {
objectPath = Strings.concat(objectPath, ThreadLocalDateFormatter.numericDateFormat(new Date()) , "/");
}
String originalFilename = file.getOriginalFilename();
String suffix = originalFilename.substring(originalFilename.lastIndexOf('.')).toLowerCase();
String filename = UUID.randomUUID() + suffix;
String fileObject = Strings.concat(objectPath, filename);
AssetsUtils.checkFileExtention(suffix, "minio", params);
if (0 < fileUploadLimitMbSize && file.getSize() > MemCapacity.longBytesOfMB(fileUploadLimitMbSize)) { // 文件大小限制
throw new BizException("文件大小超出最大上传限制!");
}
if (doOriginReferCheck) {
// TODO
}
try {
minioClient.putObject(PutObjectArgs.builder().bucket(thisUploadBucket) // 存储桶
.object(fileObject) // 文件名
.stream(file.getInputStream(), file.getSize(), -1) // 文件内容
.contentType(file.getContentType()) // 文件类型
.build());
String protocol = Strings.endsWithIgnoreCase(cdnProtocol, "://") ? cdnProtocol : Strings.concat(cdnProtocol, "://");
// 上传图片得到
String url = String.format("%s/%s/%s", Strings.concat(protocol, cdnDomain),
thisUploadBucket, fileObject);
return url;
} catch (Exception e) {
log.error("MinioOssClient upload MultipartFile: " + e.getMessage(), e);
throw new BizException("MinioClient 上传异常!", e);
}
}
@Override
public String upload(byte[] bytes, String filename, Map params) {
MinioClient minioClient = MinioConfig.getInstance();
if (null == minioClient) {
throw new BizException("MinioClient 尚未初始化!");
}
if (null == bytes || 0 >= bytes.length) {
throw new BizException("上传文件不能为空!");
}
String bucketVar = (String) params.getOrDefault(OssConstants.BUCKET_NAME_PARAM_KEY, Strings.EMPTY);
String thisUploadBucket = Strings.isBlank(bucketVar) ? defaultBucket : bucketVar;
String filenameLastSegment = filename;
if (filename.lastIndexOf("/") >= 0) {
filenameLastSegment = filename.substring(filename.lastIndexOf("/") + 1);
}
String fileExtention = Files.getExtension(filenameLastSegment);
String contentType = java.util.Objects.toString(params.get(OssConstants.CONTENT_TYPE_PARAM_KEY), Strings.EMPTY);
if (Strings.isBlank(contentType)) {
contentType = Files.getFileContentType(fileExtention);
}
String finalFilename = Strings.concat(UUID.randomUUID(), fileExtention);
String objectPath = Strings.EMPTY;
if (fileArchivedByDate) {
objectPath = Strings.concat(objectPath, ThreadLocalDateFormatter.numericDateFormat(new Date()) , "/");
}
String fileObject = Strings.concat(objectPath, finalFilename);
if (bytes.length > MemCapacity.longBytesOfMB(fileUploadLimitMbSize)) { // 文件大小限制
throw new BizException("文件大小超出最大上传限制!");
}
if (doOriginReferCheck) {
// TODO
}
try {
if (Strings.isNotBlank(contentType)) {
minioClient.putObject(PutObjectArgs.builder().bucket(thisUploadBucket) // 存储桶
.object(fileObject) // 文件名
.stream(new ByteArrayInputStream(bytes), bytes.length, -1) // 文件内容
.contentType(contentType) // 文件类型
.build());
} else {
minioClient.putObject(PutObjectArgs.builder().bucket(thisUploadBucket) // 存储桶
.object(fileObject) // 文件名
.stream(new ByteArrayInputStream(bytes), bytes.length, -1) // 文件内容
.build());
}
String protocol = Strings.endsWithIgnoreCase(cdnProtocol, "://") ? cdnProtocol : Strings.concat(cdnProtocol, "://");
String url = String.format("%s/%s/%s", Strings.concat(protocol, cdnDomain),
thisUploadBucket, fileObject);
return url;
} catch (Exception e) {
log.error("MinioOssClient upload byte[]: " + e.getMessage(), e);
throw new BizException("MinioClient 上传异常!", e);
}
}
DelayQueueProducer getDelayQueueProducer() {
return BeanFactory.getInstance().getBean(DelayQueueProducer.class);
}
}