Guwan-smartSchool/shapelight-admin/src/main/java/net/shapelight/common/config/MinioUtils.java

82 lines
2.9 KiB
Java
Raw Normal View History

2023-09-20 14:35:52 +08:00
package net.shapelight.common.config;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Base64;
@Slf4j
@Component
public class MinioUtils {
@Autowired
private MinioConfig minioConfig;
@Autowired
private MinioClient minioClient;
public String getFileBase64(String url){
String base64Image = "";
InputStream inStream = null;
ByteArrayOutputStream outStream = null;
try {
minioClient.statObject(minioConfig.getBucketName(), url);
inStream = minioClient.getObject(minioConfig.getBucketName(), url);
outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, length);
}
base64Image = Base64.getEncoder().encodeToString(outStream.toByteArray());
} catch (Exception e) {
log.error("Minio文件不存在" + url);
e.printStackTrace();
} finally {
if (inStream != null) {
try {
inStream.close();
} catch (IOException e) {
log.error("inputStream close IOException:" + e.getMessage());
}
}
if (outStream != null) {
try {
outStream.close();
} catch (IOException e) {
log.error("outStream close IOException:" + e.getMessage());
}
}
}
return base64Image;
}
public boolean saveFileByBase64(String fileBase64,String fileName,String contentType){
if(fileBase64!=null && !fileBase64.isEmpty()){
try {
byte[] b = Base64.getDecoder().decode(fileBase64.replace("\n", ""));
InputStream inputStream = new ByteArrayInputStream(b);
PutObjectOptions putObjectOptions = new PutObjectOptions(b.length, -1);
// putObjectOptions.setContentType("image/jpeg");
putObjectOptions.setContentType(contentType);
minioClient.putObject(
minioConfig.getBucketName(), fileName, inputStream, putObjectOptions);
inputStream.close();
return true;
} catch (Exception e) {
e.printStackTrace();
log.error(e.getMessage());
return false;
}
}else{
log.debug("Minio文件base64为空不能写入");
return false;
}
}
}