Java操作MinIo上传下载文件

介绍与安装请查看另一篇文章
MinIo安装及其使用指南

环境准备

依赖 版本
Java 1.8
minio 7.0.2
maven 3.3.9
SpringBoot 2.4

创建项目

完整pom文件如下

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.4.2version>
        <relativePath/> 
    parent>
    <groupId>com.minio.demogroupId>
    <artifactId>demoartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>demoname>
    <description>Demo project for Spring Bootdescription>
    <properties>
        <java.version>1.8java.version>
    properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starterartifactId>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-devtoolsartifactId>
            <scope>runtimescope>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
        dependency>
        <dependency>
            <groupId>io.miniogroupId>
            <artifactId>minioartifactId>
            <version>7.0.2version>
        dependency>
        <dependency>
            <groupId>org.apache.commonsgroupId>
            <artifactId>commons-lang3artifactId>
        dependency>
        <dependency>
            <groupId>cn.hutoolgroupId>
            <artifactId>hutool-allartifactId>
            <version>5.4.4version>
        dependency>
        <dependency>
            <groupId>javax.persistencegroupId>
            <artifactId>persistence-apiartifactId>
            <version>1.0version>
            <scope>compilescope>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>
        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.73version>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombokgroupId>
                            <artifactId>lombokartifactId>
                        exclude>
                    excludes>
                configuration>
            plugin>
        plugins>
    build>

project>

配置文件
server:
  port: 11808

minio:
  endpoint: http://192.168.31.150/
  port: 9000
  accessKey: AKIAIOSFODNN7EXAMPLE
  secretKey: wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
  secure: false
  bucketName: "demo"

代码是之前写的demo,有一部分是参考其他博主写的代码,但由于时间有些久远,不记得是哪位博主了,因此未未能注明来源,还望抱歉,另外,以下代码经过postman测试,没什么太大的问题.不过仅供参考,请结合实际业务编写.

Minio配置类
import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

@Data
@Component
@ConfigurationProperties(prefix = "minio")
public class MinioConfig {

    // endPoint是一个URL,域名,IPv4或者IPv6地址
    private String endpoint;

    // TCP/IP端口号
    private int port;

    private String accessKey;

    private String secretKey;

    // 如果是true,则用的是https而不是http,默认值是true
    private Boolean secure;

    // 默认存储桶
    private String bucketName;

    @Bean
    public MinioClient getMinioClient() throws InvalidEndpointException, InvalidPortException {
        MinioClient minioClient = new MinioClient(endpoint, port, accessKey, secretKey, secure);
        return minioClient;
    }
}
MinioService
import io.minio.ObjectStat;
import io.minio.Result;
import io.minio.errors.*;
import io.minio.messages.Item;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public interface MinioService {


    /**
     * 判断 bucket是否存在
     *
     * @param bucketName
     * @return
     */
    boolean bucketExists(String bucketName);

    /**
     * 创建 bucket
     *
     * @param bucketName
     */
    void makeBucket(String bucketName);

    /**
     * 文件上传
     *
     * @param bucketName
     * @param objectName
     * @param filename
     */
    void putObject(String bucketName, String objectName, String filename);

    /**
     * 文件上传
     *
     * @param bucketName
     * @param objectName
     * @param stream
     */
    void putObject(String bucketName, String objectName, InputStream stream, String contentType);

    /**
     * 文件上传
     *
     * @param bucketName
     * @param multipartFile
     */
    void putObject(String bucketName, MultipartFile multipartFile, String filename);

    /**
     * 删除文件
     * @param bucketName
     * @param objectName
     */
    boolean removeObject(String bucketName,String objectName);

    /**
     * 下载文件
     *
     * @param fileName
     * @param originalName
     * @param response
     */
    void downloadFile(String bucketName, String fileName, String originalName, HttpServletResponse response);

    /**
     * 获取文件路径
     * @param bucketName
     * @param objectName
     * @return
     */
    String getObjectUrl(String bucketName,String objectName);


    /**
     * @description:  文件下载
     * @param:  bucketName
      objectName
     * @return: io.minio.ObjectStat
     * @author yangc
     * @date: 2020-10-20 20:24
     */
    ObjectStat statObject(String bucketName, String objectName);

    /**
     * 以流的形式获取一个文件对象
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @return
     */
    InputStream getObject(String bucketName, String objectName);


    /**
     * 列出存储桶中所有对象
     *
     * @param bucketName 存储桶名称
     * @return
     */
    Iterable<Result<Item>> listObjects(String bucketName);


    /**
     * 生成一个给HTTP GET请求用的presigned URL
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @param expires 失效时间(以秒为单位),默认是7天,不得大于七天
     * @return
     */
    String presignedGetObject(String bucketName, String objectName, Integer expires);


    /**
     * 设置存储桶策略
     *
     * @param bucketName 存储桶名称
     * @return
     */
    void setBucketPolicy(String bucketName, String policy) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException;


    /**
     * 获取存储桶策略
     *
     * @param bucketName 存储桶名称
     * @return
     */
    String getBucketPolicy(String bucketName) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, BucketPolicyTooLargeException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException;
}

MinioServiceIpl
import com.minio.demo.service.MinioService;
import com.minio.demo.utils.MinioUtil;
import io.minio.ObjectStat;
import io.minio.Result;
import io.minio.errors.*;
import io.minio.messages.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

@Service
public class MinioServiceImpl implements MinioService {

    @Autowired
    private MinioUtil minioUtil;

    /**
     * 判断 bucket是否存在
     *
     * @param bucketName
     * @return
     */
    @Override
    public boolean bucketExists(String bucketName) {
        return minioUtil.bucketExists(bucketName);
    }

    /**
     * 创建 bucket
     *
     * @param bucketName
     */
    @Override
    public void makeBucket(String bucketName) {
        minioUtil.makeBucket(bucketName);
    }

    /**
     * 文件上传
     *
     * @param bucketName
     * @param objectName
     * @param filename
     */
    @Override
    public void putObject(String bucketName, String objectName, String filename) {
        minioUtil.putObject(bucketName, objectName, filename);
    }


    @Override
    public void putObject(String bucketName, String objectName, InputStream stream, String contentType) {
        minioUtil.putObject(bucketName, objectName, stream, contentType);
    }

    /**
     * 文件上传
     *
     * @param bucketName
     * @param multipartFile
     */
    @Override
    public void putObject(String bucketName, MultipartFile multipartFile, String filename) {
        minioUtil.putObject(bucketName, multipartFile, filename);
    }

    /**
     * 删除文件
     * @param bucketName
     * @param objectName
     */
    @Override
    public boolean removeObject(String bucketName,String objectName) {
        return minioUtil.removeObject(bucketName,objectName);
    }

    /**
     * 下载文件
     *
     * @param fileName
     * @param originalName
     * @param response
     */
    @Override
    public void downloadFile(String bucketName, String fileName, String originalName, HttpServletResponse response) {
        minioUtil.downloadFile(bucketName,fileName, originalName, response);
    }

    /**
     * 获取文件路径
     * @param bucketName
     * @param objectName
     * @return
     */
    @Override
    public String getObjectUrl(String bucketName,String objectName) {
        return minioUtil.getObjectUrl(bucketName,objectName);
    }

    /**
     * @param bucketName
     * @param objectName
     * @description: 文件下载
     * @param: bucketName
     * objectName
     * @return: io.minio.ObjectStat
     * @author yangc
     * @date: 2020-10-20 20:24
     */
    @Override
    public ObjectStat statObject(String bucketName, String objectName) {
        return minioUtil.statObject(bucketName,objectName);
    }

    /**
     * 以流的形式获取一个文件对象
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @return
     */
    @Override
    public InputStream getObject(String bucketName, String objectName) {
        return minioUtil.getObject(bucketName,objectName);
    }

    /**
     * 列出存储桶中所有对象
     *
     * @param bucketName 存储桶名称
     * @return
     */
    @Override
    public Iterable<Result<Item>> listObjects(String bucketName) {
        return minioUtil.listObjects(bucketName);
    }

    /**
     * 生成一个给HTTP GET请求用的presigned URL
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @param expires    失效时间(以秒为单位),默认是7天,不得大于七天
     * @return
     */
    @Override
    public String presignedGetObject(String bucketName, String objectName, Integer expires) {
        return minioUtil.presignedGetObject(bucketName, objectName, expires);
    }

    /**
     * 设置存储桶策略
     *
     * @param bucketName 存储桶名称
     * @param policy
     * @return
     */
    @Override
    public void setBucketPolicy(String bucketName, String policy) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
        minioUtil.setBucketPolicy(bucketName, policy);
    }

    /**
     * 获取存储桶策略
     *
     * @param bucketName 存储桶名称
     * @return
     */
    @Override
    public String getBucketPolicy(String bucketName) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, BucketPolicyTooLargeException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
        return minioUtil.getBucketPolicy(bucketName);
    }


}

MinioUtil
import io.minio.MinioClient;
import io.minio.ObjectStat;
import io.minio.PutObjectOptions;
import io.minio.Result;
import io.minio.errors.*;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteError;
import io.minio.messages.Item;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

/**
 * @PackageName: com.hope.minio.utils
 * @ClassName: MinioUtil
 * @Author Hope
 * @Date 2020/7/27 11:43
 * @Description: MinioUtil
 */
@Component
public class MinioUtil {

    @Autowired
    private MinioClient minioClient;

    private static final int DEFAULT_EXPIRY_TIME = 7 * 24 * 3600;

    /**
     * 检查存储桶是否存在
     *
     * @param bucketName 存储桶名称
     * @return
     */
    @SneakyThrows
    public boolean bucketExists(String bucketName) {
        boolean flag = false;
        flag = minioClient.bucketExists(bucketName);
        if (flag) {
            return true;
        }
        return false;
    }

    /**
     * 创建存储桶
     *
     * @param bucketName 存储桶名称
     */
    @SneakyThrows
    public boolean makeBucket(String bucketName) {
        boolean flag = bucketExists(bucketName);
        if (!flag) {
            minioClient.makeBucket(bucketName);
            return true;
        } else {
            return false;
        }
    }

    /**
     * 列出所有存储桶名称
     *
     * @return
     */
    @SneakyThrows
    public List<String> listBucketNames() {
        List<Bucket> bucketList = listBuckets();
        List<String> bucketListName = new ArrayList<>();
        for (Bucket bucket : bucketList) {
            bucketListName.add(bucket.name());
        }
        return bucketListName;
    }

    /**
     * 列出所有存储桶
     *
     * @return
     */
    @SneakyThrows
    public List<Bucket> listBuckets() {
        return minioClient.listBuckets();
    }

    /**
     * 删除存储桶
     *
     * @param bucketName 存储桶名称
     * @return
     */
    @SneakyThrows
    public boolean removeBucket(String bucketName) {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            Iterable<Result<Item>> myObjects = listObjects(bucketName);
            for (Result<Item> result : myObjects) {
                Item item = result.get();
                // 有对象文件,则删除失败
                if (item.size() > 0) {
                    return false;
                }
            }
            // 删除存储桶,注意,只有存储桶为空时才能删除成功。
            minioClient.removeBucket(bucketName);
            flag = bucketExists(bucketName);
            if (!flag) {
                return true;
            }

        }
        return false;
    }

    /**
     * 列出存储桶中的所有对象名称
     *
     * @param bucketName 存储桶名称
     * @return
     */
    @SneakyThrows
    public List<String> listObjectNames(String bucketName) {
        List<String> listObjectNames = new ArrayList<>();
        boolean flag = bucketExists(bucketName);
        if (flag) {
            Iterable<Result<Item>> myObjects = listObjects(bucketName);
            for (Result<Item> result : myObjects) {
                Item item = result.get();
                listObjectNames.add(item.objectName());
            }
        }
        return listObjectNames;
    }

    /**
     * 列出存储桶中的所有对象
     *
     * @param bucketName 存储桶名称
     * @return
     */
    @SneakyThrows
    public Iterable<Result<Item>> listObjects(String bucketName) {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            return minioClient.listObjects(bucketName);
        }
        return null;
    }

    /**
     * 通过文件上传到对象
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @param fileName   File name
     * @return
     */
    @SneakyThrows
    public boolean putObject(String bucketName, String objectName, String fileName) {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            minioClient.putObject(bucketName, objectName, fileName, null);
            ObjectStat statObject = statObject(bucketName, objectName);
            if (statObject != null && statObject.length() > 0) {
                return true;
            }
        }
        return false;

    }

    /**
     * 文件上传
     *
     * @param bucketName
     * @param multipartFile
     */
    @SneakyThrows
    public void putObject(String bucketName, MultipartFile multipartFile, String filename) {
        PutObjectOptions putObjectOptions = new PutObjectOptions(multipartFile.getSize(), PutObjectOptions.MIN_MULTIPART_SIZE);
        putObjectOptions.setContentType(multipartFile.getContentType());
        minioClient.putObject(bucketName, filename, multipartFile.getInputStream(), putObjectOptions);
    }


    /**
     * 通过InputStream上传对象
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @param stream     要上传的流
     * @param stream     要上传的文件类型 MimeTypeUtils.IMAGE_JPEG_VALUE
     * @return
     */
    @SneakyThrows
    public boolean putObject(String bucketName, String objectName, InputStream stream,String contentType) {
        boolean flag = bucketExists(bucketName);
        if (flag) {
        	PutObjectOptions putObjectOptions = new PutObjectOptions(stream.available(), -1);
        	/**
        	 * 开启公共类功能设置setContentType
        	 */
        	if (StringUtils.isNotBlank(contentType)) {
        		putObjectOptions.setContentType(contentType);
			}
            minioClient.putObject(bucketName, objectName, stream, putObjectOptions);
            ObjectStat statObject = statObject(bucketName, objectName);
            if (statObject != null && statObject.length() > 0) {
                return true;
            }
        }
        return false;
    }
    
	/**
     * 以流的形式获取一个文件对象
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @return
     */
    @SneakyThrows
    public InputStream getObject(String bucketName, String objectName) {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            ObjectStat statObject = statObject(bucketName, objectName);
            if (statObject != null && statObject.length() > 0) {
                InputStream stream = minioClient.getObject(bucketName, objectName);
                return stream;
            }
        }
        return null;
    }

    /**
     * 以流的形式获取一个文件对象(断点下载)
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @param offset     起始字节的位置
     * @param length     要读取的长度 (可选,如果无值则代表读到文件结尾)
     * @return
     */
    @SneakyThrows
    public InputStream getObject(String bucketName, String objectName, long offset, Long length) {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            ObjectStat statObject = statObject(bucketName, objectName);
            if (statObject != null && statObject.length() > 0) {
                InputStream stream = minioClient.getObject(bucketName, objectName, offset, length);
                return stream;
            }
        }
        return null;
    }

    /**
     * 下载并将文件保存到本地
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @param fileName   File name
     * @return
     */
    @SneakyThrows
    public boolean getObject(String bucketName, String objectName, String fileName) {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            ObjectStat statObject = statObject(bucketName, objectName);
            if (statObject != null && statObject.length() > 0) {
                minioClient.getObject(bucketName, objectName, fileName);
                return true;
            }
        }
        return false;
    }

    /**
     * 删除一个对象
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     */
    @SneakyThrows
    public boolean removeObject(String bucketName, String objectName) {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            minioClient.removeObject(bucketName, objectName);
            return true;
        }
        return false;
    }

    /**
     * 删除指定桶的多个文件对象,返回删除错误的对象列表,全部删除成功,返回空列表
     *
     * @param bucketName  存储桶名称
     * @param objectNames 含有要删除的多个object名称的迭代器对象
     * @return
     */
    @SneakyThrows
    public List<String> removeObject(String bucketName, List<String> objectNames) {
        List<String> deleteErrorNames = new ArrayList<>();
        boolean flag = bucketExists(bucketName);
        if (flag) {
            Iterable<Result<DeleteError>> results = minioClient.removeObjects(bucketName, objectNames);
            for (Result<DeleteError> result : results) {
                DeleteError error = result.get();
                deleteErrorNames.add(error.objectName());
            }
        }
        return deleteErrorNames;
    }

    /**
     * 生成一个给HTTP GET请求用的presigned URL。
     * 浏览器/移动端的客户端可以用这个URL进行下载,即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间,默认值是7天。
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @param expires    失效时间(以秒为单位),默认是7天,不得大于七天
     * @return
     */
    @SneakyThrows
    public String presignedGetObject(String bucketName, String objectName, Integer expires) {
        boolean flag = bucketExists(bucketName);
        String url = "";
        if (flag) {
            if (expires < 1 || expires > DEFAULT_EXPIRY_TIME) {
                throw new InvalidExpiresRangeException(expires,
                        "expires must be in range of 1 to " + DEFAULT_EXPIRY_TIME);
            }
            url = minioClient.presignedGetObject(bucketName, objectName, expires);
        }
        return url;
    }

    /**
     * 生成一个给HTTP PUT请求用的presigned URL。
     * 浏览器/移动端的客户端可以用这个URL进行上传,即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间,默认值是7天。
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @param expires    失效时间(以秒为单位),默认是7天,不得大于七天
     * @return
     */
    @SneakyThrows
    public String presignedPutObject(String bucketName, String objectName, Integer expires) {
        boolean flag = bucketExists(bucketName);
        String url = "";
        if (flag) {
            if (expires < 1 || expires > DEFAULT_EXPIRY_TIME) {
                throw new InvalidExpiresRangeException(expires,
                        "expires must be in range of 1 to " + DEFAULT_EXPIRY_TIME);
            }
            url = minioClient.presignedPutObject(bucketName, objectName, expires);
        }
        return url;
    }

    /**
     * 获取对象的元数据
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @return
     */
    @SneakyThrows
    public ObjectStat statObject(String bucketName, String objectName) {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            ObjectStat statObject = minioClient.statObject(bucketName, objectName);
            return statObject;
        }
        return null;
    }

    /**
     * 文件访问路径
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @return
     */
    @SneakyThrows
    public String getObjectUrl(String bucketName, String objectName) {
        boolean flag = bucketExists(bucketName);
        String url = "";
        if (flag) {
            url = minioClient.getObjectUrl(bucketName, objectName);
        }
        return url;
    }


    /**
     * 设置存储桶策略
     *
     * @param bucketName 存储桶名称
     * @param policy 存储桶里的对象名称
     */
    public void setBucketPolicy(String bucketName, String policy) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {

        minioClient.setBucketPolicy(bucketName, policy);
    }


    /**
     * 获取存储桶策略
     *
     * @param bucketName 存储桶名称
     * @return
     */
    public String getBucketPolicy(String bucketName) throws IOException, InvalidKeyException, InvalidResponseException, BucketPolicyTooLargeException, NoSuchAlgorithmException, InternalException, XmlParserException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException {

        return minioClient.getBucketPolicy(bucketName);
    }



    public void downloadFile(String bucketName, String fileName, String originalName, HttpServletResponse response) {
        try {

            InputStream file = minioClient.getObject(bucketName, fileName);
            String filename = new String(fileName.getBytes("ISO8859-1"), StandardCharsets.UTF_8);
            if (StringUtils.isNotEmpty(originalName)) {
                fileName = originalName;
            }
            response.setHeader("Content-Disposition", "attachment;filename=" + filename);
            ServletOutputStream servletOutputStream = response.getOutputStream();
            int len;
            byte[] buffer = new byte[1024];
            while ((len = file.read(buffer)) > 0) {
                servletOutputStream.write(buffer, 0, len);
            }
            servletOutputStream.flush();
            file.close();
            servletOutputStream.close();
        } catch (ErrorResponseException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

MinioController
import com.alibaba.fastjson.JSON;
import com.minio.demo.config.MinioConfig;
import com.minio.demo.result.Result;
import com.minio.demo.service.MinioService;
import com.minio.demo.utils.UploadFile;
import io.minio.ObjectStat;
import io.minio.errors.*;
import io.minio.messages.Item;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.DecimalFormat;
import java.util.*;

@RequestMapping("/minio")
@RestController
@Slf4j
public class MinioController {

    @Autowired
    private MinioService minioService;

    @Autowired
    private MinioConfig minioConfig;

    @Autowired
    private UploadFile uploadFile;


    @SneakyThrows
    @PostMapping("/file")
    public Result uploadFile(MultipartFile file, @RequestParam("bucketName") String bucketName) {
        uploadFile.uploadFile(file, bucketName);
        return Result.success();
    }

    @PostMapping("/files")
    public Result uploadFiles(@RequestParam("multipartFiles") List<MultipartFile> files, @RequestParam("bucketName") String bucketName) {
        for (MultipartFile file : files) {
            uploadFile.uploadFile(file, bucketName);
        }
        return Result.success();
    }

    @GetMapping("/file")
    public Result download(HttpServletResponse response, @RequestParam("fileName") String fileName, @RequestParam("bucketName") String bucketName, @RequestParam("fileId") String fileId) {
        try {
            //获取存储捅名
            bucketName = StringUtils.isNotBlank(bucketName) ? bucketName : minioConfig.getBucketName();
            //获取对象信息和对象的元数据。
            ObjectStat objectStat = minioService.statObject(bucketName, fileName);
            //setContentType 设置发送到客户机的响应的内容类型
            response.setContentType(objectStat.contentType());
            //设置响应头
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(objectStat.name(), "UTF-8"));
            //文件流
            InputStream object = minioService.getObject(bucketName, fileName);
            //设置文件大小
            response.setHeader("Content-Length", String.valueOf(objectStat.length()));
            IOUtils.copy(object, response.getOutputStream());
            //关闭流
            object.close();
            return Result.success();
        } catch (Exception e) {
            log.error("下载文件失败,错误信息: " + e.getMessage());
            return Result.fail("下载失败.");
        }
    }

    @DeleteMapping(value = "/file")
    public Result deleteFile(@RequestParam("bucketName") String bucketName, @RequestParam("objectName") String objectName) {
        minioService.removeObject(bucketName, objectName);
        return Result.success();
    }


    @GetMapping(value = "/file/list")
    public Result<List<Object>> getFileList(@RequestParam("bucketName") String bucketName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
        try {
            //获取存储捅名
            bucketName = StringUtils.isNotBlank(bucketName) ? bucketName : minioConfig.getBucketName();
            //列出存储桶中所有对象
            Iterable<io.minio.Result<Item>> results = minioService.listObjects(bucketName);
            //迭代器
            Iterator<io.minio.Result<Item>> iterator = results.iterator();

            List<Object> items = new ArrayList<>();

            String format = "{'fileName':'%s','fileSize':'%s'}";

            while (iterator.hasNext()) {
                //返回迭代中的下一个元素。
                Item item = iterator.next().get();
                //封装信息
                items.add(JSON.parse(String.format(format, "http://localhost:9000/"+bucketName+"/"+item.objectName(), formatFileSize(item.size()))));
            }
            return Result.success(items);
        } catch (Exception e) {
            log.error("获取文件列表失败,错误信息: " + e.getMessage());
            return Result.fail("获取文件列表失败");
        }
    }

    @GetMapping("/preview/file")
    public Result<List<Object>> getPreviewFile(@RequestParam("bucketName") String bucketName,
                                               @RequestParam("expires") Integer expires,
                                               @RequestParam("objectName") String objectName) {
        //获取存储捅名
        bucketName = StringUtils.isNotBlank(bucketName) ? bucketName : minioConfig.getBucketName();
        //生成一个给HTTP GET请求用的presigned URL
        String filePath = minioService.presignedGetObject(bucketName, objectName, expires);
        //封装信息
        return Result.success(filePath);
    }



    @GetMapping("/previewList")
    public Result<List<Object>> getPreviewList(@RequestParam("bucketName") String bucketName,
                                               @RequestParam("expires") Integer expires
    ) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {

        try {
            //获取存储捅名
            bucketName = StringUtils.isNotBlank(bucketName) ? bucketName : minioConfig.getBucketName();
            //列出存储桶中所有对象
            Iterable<io.minio.Result<Item>> myObjects = minioService.listObjects(bucketName);
            //迭代器
            Iterator<io.minio.Result<Item>> iterator = myObjects.iterator();
            List<Object> items = new ArrayList<>();
            String format = "{'fileName':'%s','fileSize':'%s'}";
            while (iterator.hasNext()) {
                //返回迭代中的下一个元素。
                Item item = iterator.next().get();
                //生成一个给HTTP GET请求用的presigned URL
                String filePath = minioService.presignedGetObject(bucketName, item.objectName(), expires);
                //封装信息
                items.add(JSON.parse(String.format(format, filePath, formatFileSize(item.size()))));
            }
            return Result.success(items);
        } catch (Exception e) {
            return Result.fail("生成可以预览的文件链接失败,错误信息:" + e.getMessage());
        }

    }

    /**
     * 显示文件大小信息单位
     *
     * @param fileS
     * @return
     */
    private static String formatFileSize(long fileS) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        String wrongSize = "0B";
        if (fileS == 0) {
            return wrongSize;
        }
        if (fileS < 1024) {
            fileSizeString = df.format((double) fileS) + " B";
        } else if (fileS < 1048576) {
            fileSizeString = df.format((double) fileS / 1024) + " KB";
        } else if (fileS < 1073741824) {
            fileSizeString = df.format((double) fileS / 1048576) + " MB";
        } else {
            fileSizeString = df.format((double) fileS / 1073741824) + " GB";
        }
        return fileSizeString;
    }

}
UploadFile
import cn.hutool.core.io.file.FileNameUtil;
import com.minio.demo.config.MinioConfig;
import com.minio.demo.service.MinioService;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Component
public class UploadFile {

    @Autowired
    private MinioService minioService;

    @Autowired
    private MinioConfig minioConfig;

    @SneakyThrows
    public  void uploadFile(MultipartFile file, String bucketName) {

        // 获取存储桶名称,不存在则使用默认桶名
        bucketName = StringUtils.isNotBlank(bucketName) ? bucketName : minioConfig.getBucketName();

        // 判断是否存在该存储桶
        if (!minioService.bucketExists(bucketName)) {
            // 不存在则创建
            minioService.makeBucket(bucketName);
            // 设置存储桶只读策略
            String bucketPolicy ="{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"" +
                    "Action\":[\"s3:GetBucketLocation\",\"s3:ListBucket\"],\"Resource\":[\"arn:aws:s3:::fast\"]},{\"Effect\":\"Allow\",\"" +
                    "Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::" +
                    bucketName+"/*\"]}]}";
            // 设置存储桶策略
            minioService.setBucketPolicy(bucketName,bucketPolicy);
        }
        // 原始文件名
        String fileName = file.getOriginalFilename();
        // 获取文件后缀名
        String extName = FileNameUtil.extName(fileName);
        // 定义文件路径
        String format = new SimpleDateFormat("yyyy/MM/dd/").format(new Date());
        // 定义文件修改之后的名字,去除uuid中的' - '
        String fileuuid = UUID.randomUUID().toString().replaceAll("-", "");
        // 定义新的文件名
        String objectName = format + fileuuid + "." + extName;
        //上传文件
        minioService.putObject(bucketName, file, objectName);
    }
}

测试

单个文件上传

Java操作MinIo上传下载文件_第1张图片

Java操作MinIo上传下载文件_第2张图片

多文件上传

Java操作MinIo上传下载文件_第3张图片
Java操作MinIo上传下载文件_第4张图片

文件下载

Java操作MinIo上传下载文件_第5张图片

文件删除

Java操作MinIo上传下载文件_第6张图片

生成可以预览的链接

Java操作MinIo上传下载文件_第7张图片

生成单个可预览的链接

Java操作MinIo上传下载文件_第8张图片

demo仓库地址

为方面大家查看,已经将代码上传到码云上,地址如下:

https://gitee.com/cyangDrow/min-iodemo/tree/master

你可能感兴趣的:(MinIo)