目录
拉取docker镜像
拉取稳定版本:docker pull minio/minio:RELEASE.2021-06-17T00-10-46Z-28-gac7697426
创建并运行容器: docker run -d -p 9000:9000 --name minio \
-e "MINIO_ACCESS_KEY=minio" \
-e "MINIO_SECRET_KEY=minio123" \
-v /path/to/data:/data \
-v /path/to/config:/root/.minio \
minio/minio:RELEASE.2021-06-17T00-10-46Z server /data
访问minmo系统: http://192.168.74.128:9000
minio所需要的依赖
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>7.1.0</version>
</dependency>
文件存放的位置
退出minio容器
exit
手动上传文件到minio中
public static void main(String[] args) {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream("e:\\index.js");;
//1.创建minio链接客户端
MinioClient minioClient = MinioClient.builder().credentials("minio", "minio123").endpoint("http://192.168.74.128:9000").build();
//2.上传
PutObjectArgs putObjectArgs = PutObjectArgs.builder()
.object("plugins/js/index.js")//文件名
.contentType("text/js")//文件类型
.bucket("leadnews")//桶名词 与minio创建的名词一致
.stream(fileInputStream, fileInputStream.available(), -1) //文件流
.build();
minioClient.putObject(putObjectArgs);
} catch (Exception ex) {
ex.printStackTrace();
}
}
工具类上传
yml配置
minio:
accessKey: minio
secretKey: minio123
bucket: leadnews
endpoint: http://192.168.74.128:9000
readPath: http://192.168.74.128:9000
config类
package com.heima.file.config;
import com.heima.file.service.FileStorageService;
import io.minio.MinioClient;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
@EnableConfigurationProperties({MinIOConfigProperties.class})
//当引入FileStorageService接口时
@ConditionalOnClass(FileStorageService.class)
public class MinIOConfig {
@Autowired
private MinIOConfigProperties minIOConfigProperties;
@Bean
public MinioClient buildMinioClient() {
return MinioClient
.builder()
.credentials(minIOConfigProperties.getAccessKey(), minIOConfigProperties.getSecretKey())
.endpoint(minIOConfigProperties.getEndpoint())
.build();
}
}
package com.ma.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.io.Serializable;
@Data
@ConfigurationProperties(prefix = "minio") // 文件上传 配置前缀file.oss
public class MinIOConfigProperties implements Serializable {
private String accessKey;
private String secretKey;
private String bucket;
private String endpoint;
private String readPath;
}
service类
package com.ma.service;
import java.io.InputStream;
/**
* @author itheima
*/
public interface FileStorageService {
/**
* 上传图片文件
* @param prefix 文件前缀
* @param filename 文件名
* @param inputStream 文件流
* @return 文件全路径
*/
public String uploadImgFile(String prefix, String filename,InputStream inputStream);
/**
* 上传html文件
* @param prefix 文件前缀
* @param filename 文件名
* @param inputStream 文件流
* @return 文件全路径
*/
public String uploadHtmlFile(String prefix, String filename,InputStream inputStream);
/**
* 删除文件
* @param pathUrl 文件全路径
*/
public void delete(String pathUrl);
/**
* 下载文件
* @param pathUrl 文件全路径
* @return
*
*/
public byte[] downLoadFile(String pathUrl);
}
package com.ma.service.impl;
import com.ma.config.MinIOConfig;
import com.ma.config.MinIOConfigProperties;
import com.ma.service.FileStorageService;
import io.minio.GetObjectArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.RemoveObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
@Slf4j
@EnableConfigurationProperties(MinIOConfigProperties.class)
@Import(MinIOConfig.class)
@Service
public class MinIOFileStorageService implements FileStorageService {
@Autowired
private MinioClient minioClient;
@Autowired
private MinIOConfigProperties minIOConfigProperties;
private final static String separator = "/";
/**
* @param dirPath
* @param filename yyyy/mm/dd/file.jpg
* @return
*/
public String builderFilePath(String dirPath,String filename) {
StringBuilder stringBuilder = new StringBuilder(50);
if(!StringUtils.isEmpty(dirPath)){
stringBuilder.append(dirPath).append(separator);
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
String todayStr = sdf.format(new Date());
stringBuilder.append(todayStr).append(separator);
stringBuilder.append(filename);
return stringBuilder.toString();
}
/**
* 上传图片文件
* @param prefix 文件前缀
* @param filename 文件名
* @param inputStream 文件流
* @return 文件全路径
*/
@Override
public String uploadImgFile(String prefix, String filename,InputStream inputStream) {
String filePath = builderFilePath(prefix, filename);
try {
PutObjectArgs putObjectArgs = PutObjectArgs.builder()
.object(filePath)
.contentType("image/jpg")
.bucket(minIOConfigProperties.getBucket()).stream(inputStream,inputStream.available(),-1)
.build();
minioClient.putObject(putObjectArgs);
StringBuilder urlPath = new StringBuilder(minIOConfigProperties.getReadPath());
urlPath.append(separator+minIOConfigProperties.getBucket());
urlPath.append(separator);
urlPath.append(filePath);
return urlPath.toString();
}catch (Exception ex){
log.error("minio put file error.",ex);
throw new RuntimeException("上传文件失败");
}
}
/**
* 上传html文件
* @param prefix 文件前缀
* @param filename 文件名
* @param inputStream 文件流
* @return 文件全路径
*/
@Override
public String uploadHtmlFile(String prefix, String filename,InputStream inputStream) {
String filePath = builderFilePath(prefix, filename);
try {
PutObjectArgs putObjectArgs = PutObjectArgs.builder()
.object(filePath)
.contentType("text/html")
.bucket(minIOConfigProperties.getBucket()).stream(inputStream,inputStream.available(),-1)
.build();
minioClient.putObject(putObjectArgs);
StringBuilder urlPath = new StringBuilder(minIOConfigProperties.getReadPath());
urlPath.append(separator+minIOConfigProperties.getBucket());
urlPath.append(separator);
urlPath.append(filePath);
return urlPath.toString();
}catch (Exception ex){
log.error("minio put file error.",ex);
ex.printStackTrace();
throw new RuntimeException("上传文件失败");
}
}
/**
* 删除文件
* @param pathUrl 文件全路径
*/
@Override
public void delete(String pathUrl) {
String key = pathUrl.replace(minIOConfigProperties.getEndpoint()+"/","");
int index = key.indexOf(separator);
String bucket = key.substring(0,index);
String filePath = key.substring(index+1);
// 删除Objects
RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder().bucket(bucket).object(filePath).build();
try {
minioClient.removeObject(removeObjectArgs);
} catch (Exception e) {
log.error("minio remove file error. pathUrl:{}",pathUrl);
e.printStackTrace();
}
}
/**
* 下载文件
* @param pathUrl 文件全路径
* @return 文件流
*
*/
@Override
public byte[] downLoadFile(String pathUrl) {
String key = pathUrl.replace(minIOConfigProperties.getEndpoint()+"/","");
int index = key.indexOf(separator);
String bucket = key.substring(0,index);
String filePath = key.substring(index+1);
InputStream inputStream = null;
try {
inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(minIOConfigProperties.getBucket()).object(filePath).build());
} catch (Exception e) {
log.error("minio down file error. pathUrl:{}",pathUrl);
e.printStackTrace();
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buff = new byte[100];
int rc = 0;
while (true) {
try {
if (!((rc = inputStream.read(buff, 0, 100)) > 0)) break;
} catch (IOException e) {
e.printStackTrace();
}
byteArrayOutputStream.write(buff, 0, rc);
}
return byteArrayOutputStream.toByteArray();
}
}
启动类
@SpringBootApplication
@ComponentScan(basePackages = {"com.ma.config", "com.ma.service"})
public class SpringBootTest01Application {
public static void main(String[] args) {
SpringApplication.run(SpringBootTest01Application.class, args);
}
}
测试类
图片
package com.ma.springboottest01;
import com.ma.service.FileStorageService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.FileInputStream;
import java.io.InputStream;
@SpringBootTest
class SpringBootTest01ApplicationTests {
@Autowired
private FileStorageService fileStorageService;
@Test
void contextLoads() {
// 示例用法
try {
// 创建一个InputStream,例如从本地文件获取
InputStream fileInputStream = new FileInputStream("D:\\Image\\星空.jpg");
// 调用uploadImgFile方法进行文件上传
String prefix = "user_images/"; // 设置文件前缀
String filename = "unique_image_name.jpg"; // 设置文件名
// String url = uploadImgFile(prefix, filename, fileInputStream);
// url现在包含了上传文件的访问路径
String url = fileStorageService.uploadImgFile(prefix, filename, fileInputStream);
System.out.println("File uploaded successfully. URL: " + url);
} catch (Exception e) {
// 处理上传失败的情况
e.printStackTrace();
}
}
}
视频
package com.ma.springboottest01;
import com.ma.service.FileStorageService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.FileInputStream;
import java.io.InputStream;
@SpringBootTest
class SpringBootTest01ApplicationTests {
@Autowired
private FileStorageService fileStorageService;
@Test
void contextLoads() {
// 示例用法
try {
// 创建一个InputStream,例如从本地文件获取
// InputStream fileInputStream = new FileInputStream("D:\\Image\\星空.jpg");
InputStream fileInputStream = new FileInputStream("D:\\video\\test.mp4");
// 调用uploadImgFile方法进行文件上传
// 设置文件前缀和文件名
String prefix = "videos/";
String filename = "example_video.mp4";
// String url = uploadImgFile(prefix, filename, fileInputStream);
// url现在包含了上传文件的访问路径
String url = fileStorageService.uploadImgFile(prefix, filename, fileInputStream);
System.out.println("File uploaded successfully. URL: " + url);
} catch (Exception e) {
// 处理上传失败的情况
e.printStackTrace();
}
}
}
删除minio服务器的文件
@Test
void t2(){
fileStorageService.delete("http://192.168.74.128:9000/leadnews/videos//2023/11/27/example_video.mp4");
}
下载minio服务器的文件
@Test
void t2() {
byte[] bytes = fileStorageService.downLoadFile("http://192.168.74.128:9000/leadnews/user_images//2023/11/27/unique_image_name.jpg");
// 保存到本地文件的示例
String localFilePath = "E:guo.jpg//"; // 替换为实际的本地文件路径
saveToFile(bytes, localFilePath);
}
public static void saveToFile(byte[] fileContent, String localFilePath) {
try (FileOutputStream fos = new FileOutputStream(localFilePath)) {
fos.write(fileContent);
System.out.println("File saved locally: " + localFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
Windows环境下的minio
minio配置
cmd管理员下配置账号密码 ,D:\software2\minio的路径
setx MINIO_ROOT_USER admin
setx MINIO_ROOT_PASSWORD 12345678
export MINIO_ACCESS_KEY=admin
export MINIO_SECRET_KEY=12345678
启动命令 :minio.exe server D:\MinIO\Data --console-address ":9000" --address ":9090"
配置bat脚本:D:\software2\minio ,路径下 ,bin目录里面创建bat脚本。logs目录同级,并创建文件minio.log
@echo off
REM 声明采用UTF-8编码
chcp 65001
echo.
echo [信息] 运行MinIO服务器。
echo.
:: 设置窗口标题
title Minio文件服务
:: 设置用户名为admin
set MINIO_ROOT_USER=admin
:: 设置密码为12345678
set MINIO_ROOT_PASSWORD=12345678
:: 切换到MinIO可执行文件所在目录
cd /d "D:\software2\minio"
:: 启动MinIO服务
start minio.exe server D:\minio\data --console-address ":9001" --address ":9000" > D:\software2\minio\logs\minio.log
pause
分析:
@echo off: 这个命令会关闭命令行窗口的回显功能,使得在执行脚本时不会在命令行窗口中显示每条命令的执行结果。
REM 声明采用UTF-8编码:这是一条注释,用来说明后面的命令会使用 UTF-8 编码。
chcp 65001: 这个命令用来设置命令行窗口的字符编码为 UTF-8。
echo.: 这个命令会输出一个空行。
echo [信息] 运行MinIO服务器。: 这个命令会输出一条提示信息,表示正在运行 MinIO 服务器。
title Minio文件服务: 这个命令会设置命令行窗口的标题为 "Minio文件服务"。
set MINIO_ROOT_USER=admin 和 set MINIO_ROOT_PASSWORD=12345678: 这两个命令用来设置 MinIO 的管理员用户名和密码。
cd /d "D:\software2\minio": 这个命令会切换到 MinIO 可执行文件所在的目录。
start minio.exe server D:\minio\data --console-address ":9001" --address ":9000" > D:\software2\minio\logs\minio.log: 这个命令会启动 MinIO 服务器,同时将日志输出到指定的文件中。
pause: 这个命令会暂停脚本的执行,直到用户按下任意键才会继续执行后面的命令。
总的来说,这个脚本的作用是启动 MinIO 服务器,并将日志输出到指定的文件中,同时提供了用户名和密码用于管理 MinIO 服务器。
顶级工具类上传(用这个)
yml配置
minio:
endpoint: http://127.0.0.1:9000 # MinIO服务地址
fileHost: http://127.0.0.1:9000 # 文件地址host
bucketName: test # 存储桶bucket名称
accessKey: admin # 用户名
secretKey: 12345678 # 密码
imgSize: 1024 # 图片大小限制,单位:m
fileSize: 1024 # 文件大小限制,单位:m
ContentType
package com.lyh.mp.config;
import org.springframework.util.StringUtils;
public enum ContentType {
DEFAULT("default","application/octet-stream"),
JPG("jpg", "image/jpeg"),
TIFF("tiff", "image/tiff"),
GIF("gif", "image/gif"),
JFIF("jfif", "image/jpeg"),
PNG("png", "image/png"),
TIF("tif", "image/tiff"),
ICO("ico", "image/x-icon"),
JPEG("jpeg", "image/jpeg"),
WBMP("wbmp", "image/vnd.wap.wbmp"),
FAX("fax", "image/fax"),
NET("net", "image/pnetvue"),
JPE("jpe", "image/jpeg"),
RP("rp", "image/vnd.rn-realpix"),
MP4("mp4", "video/mp4");
private String prefix;
private String type;
public static String getContentType(String prefix){
if(StringUtils.isEmpty(prefix)){
return DEFAULT.getType();
}
prefix = prefix.substring(prefix.lastIndexOf(".") + 1);
for (ContentType value : ContentType.values()) {
if(prefix.equalsIgnoreCase(value.getPrefix())){
return value.getType();
}
}
return DEFAULT.getType();
}
ContentType(String prefix, String type) {
this.prefix = prefix;
this.type = type;
}
public String getPrefix() {
return prefix;
}
public String getType() {
return type;
}
}
MinioConfig
package com.lyh.mp.config;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
@Data
public class MinIOConfig {
@Value("${minio.endpoint}")
private String endpoint;
@Value("${minio.fileHost}")
private String fileHost;
@Value("${minio.bucketName}")
private String bucketName;
@Value("${minio.accessKey}")
private String accessKey;
@Value("${minio.secretKey}")
private String secretKey;
@Value("${minio.imgSize}")
private Integer imgSize;
@Value("${minio.fileSize}")
private Integer fileSize;
@Bean
public MinIOUtils creatMinioClient() {
return new MinIOUtils(endpoint, bucketName, accessKey, secretKey, imgSize, fileSize);
}
}
MinioUtils
package co.yixiang.exam.common;
import io.minio.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
/**
* MinIO工具类
*/
@Slf4j
public class MinIOUtils {
private static MinioClient minioClient;
private static String endpoint;
private static String bucketName;
private static String accessKey;
private static String secretKey;
private static Integer imgSize;
private static Integer fileSize;
private static final String SEPARATOR = "/";
public MinIOUtils() {
}
public MinIOUtils(String endpoint, String bucketName, String accessKey, String secretKey, Integer imgSize, Integer fileSize) {
MinIOUtils.endpoint = endpoint;
MinIOUtils.bucketName = bucketName;
MinIOUtils.accessKey = accessKey;
MinIOUtils.secretKey = secretKey;
MinIOUtils.imgSize = imgSize;
MinIOUtils.fileSize = fileSize;
createMinioClient();
}
/**
* 创建基于Java端的MinioClient
*/
public void createMinioClient() {
try {
if (null == minioClient) {
log.info("开始创建 MinioClient...");
minioClient = MinioClient
.builder()
.endpoint(endpoint)
.credentials(accessKey, secretKey)
.build();
createBucket(bucketName);
log.info("创建完毕 MinioClient...");
}
} catch (Exception e) {
log.error("MinIO服务器异常:{}", e);
}
}
/**
* 获取上传文件前缀路径
* @return
*/
public static String getBasisUrl() {
return endpoint + SEPARATOR + bucketName + SEPARATOR;
}
/****************************** Operate Bucket Start ******************************/
/**
* 启动SpringBoot容器的时候初始化Bucket
* 如果没有Bucket则创建
* @throws Exception
*/
private static void createBucket(String bucketName) throws Exception {
if (!bucketExists(bucketName)) {
minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
}
}
/**
* 判断Bucket是否存在,true:存在,false:不存在
* @return
* @throws Exception
*/
public static boolean bucketExists(String bucketName) throws Exception {
return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
}
/**
* 获得Bucket的策略
* @param bucketName
* @return
* @throws Exception
*/
public static String getBucketPolicy(String bucketName) throws Exception {
String bucketPolicy = minioClient
.getBucketPolicy(
GetBucketPolicyArgs
.builder()
.bucket(bucketName)
.build()
);
return bucketPolicy;
}
/**
* 获得所有Bucket列表
* @return
* @throws Exception
*/
public static List<Bucket> getAllBuckets() throws Exception {
return minioClient.listBuckets();
}
/**
* 根据bucketName获取其相关信息
* @param bucketName
* @return
* @throws Exception
*/
public static Optional<Bucket> getBucket(String bucketName) throws Exception {
return getAllBuckets().stream().filter(b -> b.name().equals(bucketName)).findFirst();
}
/**
* 根据bucketName删除Bucket,true:删除成功; false:删除失败,文件或已不存在
* @param bucketName
* @throws Exception
*/
public static void removeBucket(String bucketName) throws Exception {
minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
}
/****************************** Operate Bucket End ******************************/
/****************************** Operate Files Start ******************************/
/**
* 判断文件是否存在
* @param bucketName 存储桶
* @param objectName 文件名
* @return
*/
public static boolean isObjectExist(String bucketName, String objectName) {
boolean exist = true;
try {
minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
} catch (Exception e) {
exist = false;
}
return exist;
}
/**
* 判断文件夹是否存在
* @param bucketName 存储桶
* @param objectName 文件夹名称
* @return
*/
public static boolean isFolderExist(String bucketName, String objectName) {
boolean exist = false;
try {
Iterable<Result<Item>> results = minioClient.listObjects(
ListObjectsArgs.builder().bucket(bucketName).prefix(objectName).recursive(false).build());
for (Result<Item> result : results) {
Item item = result.get();
if (item.isDir() && objectName.equals(item.objectName())) {
exist = true;
}
}
} catch (Exception e) {
exist = false;
}
return exist;
}
/**
* 根据文件前缀查询文件
* @param bucketName 存储桶
* @param prefix 前缀
* @param recursive 是否使用递归查询
* @return MinioItem 列表
* @throws Exception
*/
public static List<Item> getAllObjectsByPrefix(String bucketName,
String prefix,
boolean recursive) throws Exception {
List<Item> list = new ArrayList<>();
Iterable<Result<Item>> objectsIterator = minioClient.listObjects(
ListObjectsArgs.builder().bucket(bucketName).prefix(prefix).recursive(recursive).build());
if (objectsIterator != null) {
for (Result<Item> o : objectsIterator) {
Item item = o.get();
list.add(item);
}
}
return list;
}
/**
* 获取文件流
* @param bucketName 存储桶
* @param objectName 文件名
* @return 二进制流
*/
public static InputStream getObject(String bucketName, String objectName) throws Exception {
return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());
}
/**
* 断点下载
* @param bucketName 存储桶
* @param objectName 文件名称
* @param offset 起始字节的位置
* @param length 要读取的长度
* @return 二进制流
*/
public InputStream getObject(String bucketName, String objectName, long offset, long length)throws Exception {
return minioClient.getObject(
GetObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.offset(offset)
.length(length)
.build());
}
/**
* 获取路径下文件列表
* @param bucketName 存储桶
* @param prefix 文件名称
* @param recursive 是否递归查找,false:模拟文件夹结构查找
* @return 二进制流
*/
public static Iterable<Result<Item>> listObjects(String bucketName, String prefix,
boolean recursive) {
return minioClient.listObjects(
ListObjectsArgs.builder()
.bucket(bucketName)
.prefix(prefix)
.recursive(recursive)
.build());
}
/**
* 使用MultipartFile进行文件上传
* @param bucketName 存储桶
* @param file 文件名
* @param objectName 对象名
* @param contentType 类型
* @return
* @throws Exception
*/
public static ObjectWriteResponse uploadFile(String bucketName, MultipartFile file,
String objectName, String contentType) throws Exception {
InputStream inputStream = file.getInputStream();
return minioClient.putObject(
PutObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.contentType(contentType)
.stream(inputStream, inputStream.available(), -1)
.build());
}
/**
* 上传本地文件
* @param bucketName 存储桶
* @param objectName 对象名称
* @param fileName 本地文件路径
*/
public static ObjectWriteResponse uploadFile(String bucketName, String objectName,
String fileName) throws Exception {
return minioClient.uploadObject(
UploadObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.filename(fileName)
.build());
}
/**
* 通过流上传文件
*
* @param bucketName 存储桶
* @param objectName 文件对象
* @param inputStream 文件流
*/
public static ObjectWriteResponse uploadFile(String bucketName, String objectName, InputStream inputStream) throws Exception {
return minioClient.putObject(
PutObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.contentType(ContentType.getContentType(objectName))
.stream(inputStream, inputStream.available(), -1)
.build());
}
/**
* 创建文件夹或目录
* @param bucketName 存储桶
* @param objectName 目录路径
*/
public static ObjectWriteResponse createDir(String bucketName, String objectName) throws Exception {
return minioClient.putObject(
PutObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.stream(new ByteArrayInputStream(new byte[]{}), 0, -1)
.build());
}
/**
* 获取文件信息, 如果抛出异常则说明文件不存在
*
* @param bucketName 存储桶
* @param objectName 文件名称
*/
public static String getFileStatusInfo(String bucketName, String objectName) throws Exception {
return minioClient.statObject(
StatObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.build()).toString();
}
/**
* 拷贝文件
*
* @param bucketName 存储桶
* @param objectName 文件名
* @param srcBucketName 目标存储桶
* @param srcObjectName 目标文件名
*/
public static ObjectWriteResponse copyFile(String bucketName, String objectName,
String srcBucketName, String srcObjectName) throws Exception {
return minioClient.copyObject(
CopyObjectArgs.builder()
.source(CopySource.builder().bucket(bucketName).object(objectName).build())
.bucket(srcBucketName)
.object(srcObjectName)
.build());
}
/**
* 删除文件
* @param bucketName 存储桶
* @param objectName 文件名称
*/
public static void removeFile(String bucketName, String objectName) throws Exception {
minioClient.removeObject(
RemoveObjectArgs.builder()
.bucket(bucketName)
.object(objectName)
.build());
}
/**
* 批量删除文件
* @param bucketName 存储桶
* @param keys 需要删除的文件列表
* @return
*/
public static void removeFiles(String bucketName, List<String> keys) {
List<DeleteObject> objects = new LinkedList<>();
keys.forEach(s -> {
objects.add(new DeleteObject(s));
try {
removeFile(bucketName, s);
} catch (Exception e) {
log.error("批量删除失败!error:{}",e);
}
});
}
/**
* 获取文件外链
* @param bucketName 存储桶
* @param objectName 文件名
* @param expires 过期时间 <=7 秒 (外链有效时间(单位:秒))
* @return url
* @throws Exception
*/
public static String getPresignedObjectUrl(String bucketName, String objectName, Integer expires) throws Exception {
GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder().expiry(expires).bucket(bucketName).object(objectName).build();
return minioClient.getPresignedObjectUrl(args);
}
/**
* 获得文件外链
* @param bucketName
* @param objectName
* @return url
* @throws Exception
*/
public static String getPresignedObjectUrl(String bucketName, String objectName) throws Exception {
GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder()
.bucket(bucketName)
.object(objectName)
.method(Method.GET).build();
return minioClient.getPresignedObjectUrl(args);
}
/**
* 将URLDecoder编码转成UTF8
* @param str
* @return
* @throws UnsupportedEncodingException
*/
public static String getUtf8ByURLDecoder(String str) throws UnsupportedEncodingException {
String url = str.replaceAll("%(?![0-9a-fA-F]{2})", "%25");
return URLDecoder.decode(url, "UTF-8");
}
/****************************** Operate Files End ******************************/
}
controller测试
package com.lyh.mp.controller;
import com.lyh.mp.config.MinIOConfig;
import com.lyh.mp.config.MinIOUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
@RestController
@Slf4j
public class FileController {
@Autowired
private MinIOConfig minIOConfig;
@PostMapping("/upload")
public String testUpload(MultipartFile file) throws Exception {
String fileName = file.getOriginalFilename();
MinIOUtils.uploadFile(minIOConfig.getBucketName(), fileName, file.getInputStream());
//返回图片链接
String basisUrl = MinIOUtils.getBasisUrl();
String imgUrl = minIOConfig.getFileHost()+"/"+minIOConfig.getBucketName()+"/"+fileName;
return imgUrl;
}
@DeleteMapping("/delete/{fileName}")
public String deleteFile(@PathVariable String fileName) {
try {
MinIOUtils.removeFile(minIOConfig.getBucketName(), fileName);
return "File " + fileName + " has been deleted successfully.";
} catch (Exception e) {
return "Failed to delete file " + fileName + ". Error: " + e.getMessage();
}
}
@GetMapping("/download/{fileName}")
public ResponseEntity<InputStreamResource> downloadFile(@PathVariable String fileName) {
try {
// 获取文件输入流
InputStream inputStream = MinIOUtils.getObject(minIOConfig.getBucketName(), fileName);
// 设置响应头
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", fileName);
// 返回响应实体
return ResponseEntity
.ok()
.headers(headers)
.body(new InputStreamResource(inputStream));
} catch (Exception e) {
// 如果出现异常,返回错误信息
return ResponseEntity
.badRequest()
.body(null);
}
}
}
Minio,postman测试
上传
下载
删除