1.maven依赖配置
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.3.3</version>
<exclusions>
<exclusion>
<groupId>com.squareup.okhttp3</groupId>
<artifactId>okhttp</artifactId>
</exclusion>
</exclusions>
</dependency>
2.yml配置
minio:
endPoint: 服务器地址
accessKey: minioadmin
secretKey: minioadmin
bucketName: community
3.Minio代码配置
package com.iclcdp.ssdc.common.config;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.errors.ErrorResponseException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MinioConfig {
@Value("${minio.endpoint}")
String endpoint;
@Value("${minio.accessKey}")
String accessKey;
@Value("${minio.secretKey}")
String secretKey;
@Value("${minio.bucketName}")
String bucketName;
@Bean
public MinioClient minioClient() {
//新建minioClient,之后的所有minio有关操作都需使用该对象
MinioClient minioClient =
MinioClient.builder().endpoint(endpoint).credentials(accessKey, secretKey).build();
//判断默认存储桶是否存在,若不存在,调用接口进行创建
try {
//调用bucketExists接口,判断存储桶是否已经存在
if (minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build())){
return minioClient;
}
else{
//创建默认的存储桶
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
}
} catch (ErrorResponseException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return minioClient;
}
}
4.Minio工具类
package com.iclcdp.ssdc.common.utils;
import com.google.common.collect.Lists;
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.Item;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* @author qijunting_zz
* @date 2022/7/13 10:49
*/
@Slf4j
@Component
public class MinioUtils {
private static final int DEFAULT_EXPIRY_TIME = 7 * 24 * 3600;
@Autowired
private MinioClient minio;
/**
* 检查存储桶是否存在
*
* @param bucketName 存储桶名称
* @return
*/
@SneakyThrows
public boolean bucketExists(String bucketName) {
return minio.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
}
/**
* 创建存储桶
*
* @param bucketName 存储桶名称
*/
@SneakyThrows
public boolean makeBucket(String bucketName) {
boolean flag = bucketExists(bucketName);
if (flag) {
return true;
}
minio.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
return true;
}
/**
* 列出所有存储桶名称
*
* @return
*/
@SneakyThrows
public List<String> listBucketNames() {
List<Bucket> list = listBuckets();
return list.stream().filter(Objects::nonNull).map(o -> o.name()).collect(Collectors.toList());
}
/**
* 列出所有存储桶
*
* @return
*/
@SneakyThrows
public List<Bucket> listBuckets() {
return minio.listBuckets();
}
/**
* 删除存储桶
*
* @param bucketName 存储桶名称
* @return
*/
@SneakyThrows
public boolean removeBucket(String bucketName) {
Iterable<Result<Item>> myObjects = listObjects(bucketName);
for (Result<Item> result : myObjects) {
Item item = result.get();
// 有对象文件,则删除失败
if (item.size() > 0) {
return false;
}
}
// 删除存储桶,注意,只有存储桶为空时才能删除成功。
minio.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
return !bucketExists(bucketName);
}
/**
* 在test桶里创建文件夹对象
*
* @param fileName
*/
public void createFile(String fileName) {
try {
if (!bucketExists("test")) {
//minio服务器创建桶
makeBucket("test");
}
minio.putObject(
PutObjectArgs.builder().bucket("test").object(fileName).stream(
new ByteArrayInputStream(new byte[]{}), 0, -1)
.build());
} catch (ErrorResponseException e) {
e.printStackTrace();
} catch (InsufficientDataException e) {
e.printStackTrace();
} catch (InternalException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (InvalidResponseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (ServerException e) {
e.printStackTrace();
} catch (XmlParserException e) {
e.printStackTrace();
}
}
/**
* 列出存储桶中的所有对象
*
* @param bucketName 存储桶名称
* @return
*/
@SneakyThrows
public Iterable<Result<Item>> listObjects(String bucketName) {
return minio.listObjects(ListObjectsArgs.builder().bucket(bucketName).build());
}
/**
* 列出存储桶中的所有对象名称
*
* @param bucketName 存储桶名称
* @return
*/
@SneakyThrows
public List<String> listObjectNames(String bucketName) {
List<String> ret = Lists.newArrayList();
Iterable<Result<Item>> myObjects = listObjects(bucketName);
for (Result<Item> result : myObjects) {
Item item = result.get();
ret.add(item.objectName());
}
return ret;
}
/**
* 文件上传
*
* @param bucketName
* @param multipartFile
*/
@SneakyThrows
public ObjectWriteResponse putObject(String bucketName, MultipartFile multipartFile) {
PutObjectArgs args = PutObjectArgs.builder()
.bucket(bucketName)
.object(multipartFile.getName())
.contentType(multipartFile.getContentType())
.stream(multipartFile.getInputStream(), multipartFile.getSize(), -1)
.build();
return minio.putObject(args);
}
/**
* 通过InputStream上传对象
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @param in 要上传的流
* @return
*/
@SneakyThrows
public ObjectWriteResponse putObject(String bucketName, String objectName, InputStream in) {
PutObjectArgs args = PutObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.stream(in, in.available(), -1)
.build();
return minio.putObject(args);
}
/**
* 以流的形式获取一个文件对象
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @return
*/
@SneakyThrows
public InputStream getObject(String bucketName, String objectName) {
boolean flag = bucketExists(bucketName);
if (!flag) {
return null;
}
StatObjectResponse resp = statObject(bucketName, objectName);
return resp == null
? null
: minio.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
}
/**
* 获取对象的元数据
*
* @param bucketName 存储桶名称
* @param objectName 存储桶里的对象名称
* @return
*/
@SneakyThrows
public StatObjectResponse statObject(String bucketName, String objectName) {
return !bucketExists(bucketName)
? null
: minio.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
}
/**
* 删除文件
*
* @param fileName
* @return
* @throws Exception
*/
@SneakyThrows
public void removeMinio(String fileName,String bucketName) {
try {
minio.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(fileName).build());
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取文件外链
*
* @param bucketName bucket名称
* @param objectName 文件名称
* @return url
*/
@SneakyThrows
public String getObjectURL(String bucketName, String objectName) {
GetPresignedObjectUrlArgs build = GetPresignedObjectUrlArgs.builder()
.method(Method.GET)
.bucket(bucketName)
.object(objectName)
// .expiry(60 * 60 * 24)
.build();
return minio.getPresignedObjectUrl(build);
}
}
5.Minio的文件上传,下载和删除
package com.iclcdp.ssdc.community.web;
import com.iclcdp.ssdc.common.result.BaseResult;
import com.iclcdp.ssdc.common.utils.MinioUtils;
import io.minio.GetPresignedObjectUrlArgs;
import io.minio.ListObjectsArgs;
import io.minio.MinioClient;
import io.minio.Result;
import io.minio.http.Method;
import io.minio.messages.Item;
import io.swagger.annotations.Api;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.IOException;
import java.io.InputStream;
import java.util.Optional;
/**
* @author qijunting_zz
* @date 2022/7/13 15:47
*/
@Slf4j
@RequestMapping("api/community/minio")
@Api(tags = "minio相关")
@RestController
public class MinioController {
@Resource
private MinioClient minioClient;
@Autowired
private MinioUtils minioUtils;
@Value("${minio.bucketName}")
private String bucketName;
/**
* minio上传
* @param file 要上传的文件
*/
@PostMapping("/uploadFile")
public void uploadFile(MultipartFile file) {
String fileName = file.getOriginalFilename();
InputStream inputStream = null;
try {
file.getOriginalFilename();
inputStream = file.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
minioUtils.putObject(bucketName, fileName, inputStream);
}
/**
* 带url返回值的minio上传
* @param file 要上传的文件
*/
@PostMapping("/uploadFileWithUrl")
public String uploadFileWithUrl(MultipartFile file) {
String fileName = file.getOriginalFilename();
InputStream inputStream = null;
try {
file.getOriginalFilename();
inputStream = file.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
minioUtils.putObject(bucketName, fileName, inputStream);
return getObjectURL(fileName);
}
/**
* 获取文件外链
* @param objectName
*/
@GetMapping("/downloadFile")
public String downLoadFile(String objectName) {
String url = null;
try{
GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder()
.method(Method.GET)
.bucket(bucketName)
.object(objectName)
.build();
url = minioClient.getPresignedObjectUrl(args);
} catch (Exception e) {
log.error("下载链接失败",e);
}
return Optional.ofNullable(url).orElse("");
}
/**
* 删除文件
* @param objectName
*/
@PostMapping("/delete/file")
public void deleteFile(String objectName) {
minioUtils.removeMinio(objectName,bucketName);
}
/**
* 下载文件
* @param objectName
*/
@GetMapping("/get-url")
public String getObjectURL(String objectName) {
return minioUtils.getObjectURL(bucketName, objectName);
}
}
6.Minio可视化操作
在浏览器粘贴Minio服务器地址+端口号9527,输入密码。