package com.test.minio.impl;
import com.test.minio.FileService;
import io.minio.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.UUID;
/**
* @author jaingyulu
*/
@Slf4j
@Service(“minio”)
public class MinioFileServiceImpl implements FileService {
@Value(“{$minio.endpoint}”)
private String endpoint;
@Value(“{$minio.accessKeyId}”)
private String accessKeyId;
@Value(“{$minio.accessKeySecret}”)
private String accessKeySecret;
@Value(“{$minio.bucketName}”)
private String bucketName;
@Override
public String upload(InputStream inputStream, String fdsFileName, boolean img) {
try {
MinioClient minioClient =
MinioClient.builder()
.endpoint(endpoint)
.credentials(accessKeyId, accessKeySecret)
.build();
boolean found =
minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
if (found) {
log.info(“Bucket already exists.”);
} else {
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
}
if (!img) {
minioClient.putObject(
PutObjectArgs.builder()
.bucket(bucketName)
.object(fdsFileName)
.stream(inputStream, inputStream.available(), -1)
.build());
} else {
minioClient.putObject(
PutObjectArgs.builder()
.bucket(bucketName)
.object(fdsFileName)
.stream(inputStream, inputStream.available(), -1)
.contentType(“image/jpg”)
.build());
}
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return UUID.randomUUID().toString();
}
@Override
public void download(String fdsFileName, String fileName, HttpServletResponse response) {
InputStream in = null;
try {
MinioClient minioClient =
MinioClient.builder()
.endpoint(endpoint)
.credentials(accessKeyId, accessKeySecret)
.build();
StatObjectResponse objectStat = minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(fdsFileName).build());
response.setContentType(objectStat.contentType());
//response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
response.setHeader(“Content-Disposition”, “attachment;filename=” + URLEncoder.encode(fileName, “UTF-8”));
in = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fdsFileName).build());
IOUtils.copy(in, response.getOutputStream());
} catch (Exception e) {
log.error(e.getMessage());
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
log.error(e.getMessage());
}
}
}
}
@Override
public void delete(String fdsFileName) {
try {
MinioClient minioClient =
MinioClient.builder()
.endpoint(endpoint)
.credentials(accessKeyId, accessKeySecret)
.build();
minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(fdsFileName).build());
} catch (Exception e) {
e.printStackTrace();
}
}
}