MinIO文件服务器

一、MinIO 在 Windows 下的安装

1、MinIo简介

Minio 是个基于 Golang 编写的开源对象存储套件,虽然轻量,却拥有着不错的性能。

何为对象存储?
对象存储服务( Object Storage Service,OSS )是一种海量、安全、低成本、高可靠的云存储服务,适合存放任意类型的文件。容量和处理能力弹性扩展,多种存储类型供选择,全面优化存储成本。

对于中小型企业,如果不选择存储上云,那么 Minio 是个不错的选择,麻雀虽小,五脏俱全。

2、安装MinIo

a、下载安装

Windows 版下载地址:windows-amd64 版按惯例,我们将下载的 minio.exe 放在 C:\ProgramFiles\MinIO 下,因此,MINIO_HOME 就是 C:\ProgramFiles\MinIO

在这里插入图片描述

b、启动运行
  • 进入MinIo的安装根目录

  • 以管理员身份打开 cmd 执行命令:

    minio.exe server D:/minio-data
    

    提示:D:/minio-data为minio用来保存用户上传数据的目录

    启动后会打印出 AccessKey 和 SecretKey 等信息,类似如下:
    在这里插入图片描述
    MinIO Server 成功启动后访问 http://127.0.0.1:9000 ,你会看到类似如下界面:在这里插入图片描述输入用户名/密码 minioadmin/minioadmin 可以进入 web 管理系统:
    在这里插入图片描述#### c、创建桶

刚打开的时候,是没有bucket桶,可以手动或者通过java代码来创建一个桶。

创建的桶默认的权限时private私有的,外部不能访问,你可以修改桶的属性,点击manage,找到Access Policy,修改权限为public即可。

在这里插入图片描述#### f、关停 MinIO

通过命令行启动 MioIO 后,命令行窗口就被占用了。关闭命令行窗口即关闭 MioIO ,也可以使用 ctrl + c 关闭

二、springboot整合MinIO

1、引入相关依赖

 <dependency>
     <groupId>com.squareup.okhttp3</groupId>
     <artifactId>okhttp</artifactId>
     <version>4.8.1</version> <!-- minio 依赖于 okhttp 且版本较高。注意,spring-boot-dependencies 中的不够高 -->
</dependency>
<dependency>
    <groupId>io.minio</groupId>
    <artifactId>minio</artifactId>
    <version>8.3.9</version>
</dependency>

2、配置MinIo

server:
  port: 8080
spring:
  application:
    name: demo
  servlet:
    multipart:
      max-file-size: 200MB  #设置单个文件的大小  因为springboot内置tomact的的文件传输默认为10MB
      max-request-size: 500MB   #设置单次请求的文件总大小
      enabled: true    #千万注意要设置该参数,否则不生效

# minio 文件存储配置信息
minio:
  endpoint: http://127.0.0.1:9000
  accesskey: minioadmin
  secretKey: minioadmin

3、创建页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form action="minio" method="post" enctype="multipart/form-data">
        文件:<input type="file" name="pic">
        <input type="submit" value="上传">
    </form>
</body>
</html>

4、minio配置类和配置属性

/**
 * minio配置类
 */
@Configuration
@Data
@ConfigurationProperties(prefix = "minio")
public class MinIoConfig {
    private String endpoint;
    private String accesskey;
    private String secretKey;

    /**
     * 创建MinioClient对象
     * @return
     * @throws Exception
     */
    @Bean
    public MinioClient minioClient() throws Exception {
        return MinioClient.builder().endpoint(endpoint)
                .credentials(accesskey, secretKey).build();
    }
}

5、创建MinIo工具类

/**
 * MinIo工具类
 */
@Slf4j
@Component
public class MinIoUtil {
    @Resource
    private MinioClient minioClient;

    /**
     * 创建桶
     * @param bucketName 桶名
     */
    public void createBucket(String bucketName) {
        BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder().bucket(bucketName).build();
        MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder().bucket(bucketName).build();

        try {
            if (minioClient.bucketExists(bucketExistsArgs))
                return;

            minioClient.makeBucket(makeBucketArgs);
        } catch (Exception e) {
            log.error("创建桶失败:", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     * 通过 MultipartFile ,上传文件
     *
     * @param bucketName 存储桶
     * @param file       文件
     * @param objectName 对象名(文件名)
     * @param contentType   文件类型
     */
    public ObjectWriteResponse putObject(String bucketName, MultipartFile file, String objectName,String contentType) {
        try {
            InputStream inputStream = file.getInputStream();
            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .contentType(contentType)
                    .stream(inputStream, inputStream.available(), -1)
                    .build();
            return minioClient.putObject(args);
        } catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidKeyException |
                InvalidResponseException | IOException | NoSuchAlgorithmException |
                ServerException | XmlParserException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取⽂件外链
     *
     * @param bucketName bucket名称
     * @param objectName ⽂件名称
     * @param expires    过期时间 <=7
     */
    public String getObjectUrl(String bucketName, String objectName, Integer expires) {
        GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder()
                .method(Method.GET)
                .bucket(bucketName)
                .object(objectName)
                .expiry(expires)    // 单位:秒
                .build();

        try {
            return minioClient.getPresignedObjectUrl(args);
        } catch (ErrorResponseException | InsufficientDataException | InternalException |
                InvalidResponseException | InvalidKeyException | NoSuchAlgorithmException |
                IOException | XmlParserException | ServerException e) {
            throw new RuntimeException(e);
        }
    }
}

6、创建controller

@RestController
@RequestMapping("/minio")
public class MinIoController {
    @Resource
    private MinIoUtil minIoUtil;

    @RequestMapping("/send")
    public String  sendFile(MultipartFile pic){
        // 获取上传文件的名称
        String filename = pic.getOriginalFilename();
        //获得后缀
        String suffix=filename.substring(filename.lastIndexOf("."));

        // 把文件的名称设置唯一值,uuid
        String uuid = UUID.randomUUID().toString().replace("-", "");
        filename = uuid+""+suffix;

        //调用上传方法
       ObjectWriteResponse  resource=minIoUtil.putObject("picture",pic,filename,"image/jpeg");
       //获得外链
       String outside=minIoUtil.getObjectUrl("picture",filename,7);

        return outside;
    }
}

三、HTML中的Content-Type的类型

  • 常见的媒体格式类型如下:

    • text/html : HTML格式

    • text/plain :纯文本格式

    • text/xml : XML格式

    • image/gif :gif图片格式

    • image/jpeg :jpg图片格式

    • image/png:png图片格式

  • 以application开头的媒体格式类型:

    • application/xhtml+xml :XHTML格式

    • application/xml : XML数据格式

    • application/atom+xml :Atom XML聚合格式

    • application/json : JSON数据格式

    • application/pdf :pdf格式

    • application/msword : Word文档格式

    • application/octet-stream : 二进制流数据(如常见的文件下载)

    • application/x-www-form-urlencoded : 中默认的encType,form表单数据被编码为key/value格式发送到服务器(表单默认的提交数据的格式)

四、 Minio 完整工具类

/**
 * MinIo工具类
 */
@Slf4j
@Component
public class MinIoUtil {
    @Resource
    private MinioClient minioClient;

    /**
     * 创建桶
     * @param bucketName 桶名
     */
    public void createBucket(String bucketName) {
        BucketExistsArgs bucketExistsArgs = BucketExistsArgs.builder().bucket(bucketName).build();
        MakeBucketArgs makeBucketArgs = MakeBucketArgs.builder().bucket(bucketName).build();

        try {
            if (minioClient.bucketExists(bucketExistsArgs))
                return;

            minioClient.makeBucket(makeBucketArgs);
        } catch (Exception e) {
            log.error("创建桶失败:", e.getMessage());
            throw new RuntimeException(e);
        }
    }

    /**
     *判断桶是否存在
     * @param bucketName  桶名
     * @return
     */
    public boolean doesBucketExists(String bucketName) {
        BucketExistsArgs args = BucketExistsArgs.builder()
                .bucket(bucketName)
                .build();
        try {
            return minioClient.bucketExists(args);
        } catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidKeyException | InvalidResponseException | IOException | NoSuchAlgorithmException | ServerException | XmlParserException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据 bucketName 删除信息
     *
     * @param bucketName 桶名
     */
    public void removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
        } catch (ErrorResponseException | InsufficientDataException | InternalException |
                InvalidKeyException | InvalidResponseException | IOException |
                NoSuchAlgorithmException | ServerException | XmlParserException e) {
            e.printStackTrace();
        }
    }

    /**
     * 通过 MultipartFile ,上传文件
     *
     * @param bucketName 存储桶
     * @param file       文件
     * @param objectName 对象名(文件名)
     * @param contentType   文件类型
     */
    public ObjectWriteResponse putObject(String bucketName, MultipartFile file, String objectName,String contentType) {
        try {
            InputStream inputStream = file.getInputStream();
            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .contentType(contentType)
                    .stream(inputStream, inputStream.available(), -1)
                    .build();
            return minioClient.putObject(args);
        } catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidKeyException |
                InvalidResponseException | IOException | NoSuchAlgorithmException |
                ServerException | XmlParserException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 上传本地文件
     *
     * @param bucketName 存储桶
     * @param objectName 对象名称
     * @param fileName   本地文件路径
     */
    public ObjectWriteResponse putObject(String bucketName, String objectName, String fileName) {
        try {
            UploadObjectArgs args = UploadObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .filename(fileName)
                    .build();
            return minioClient.uploadObject(args);
        } catch (ErrorResponseException | InsufficientDataException | InternalException |
                InvalidKeyException | InvalidResponseException | IOException |
                NoSuchAlgorithmException | ServerException | XmlParserException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 通过流上传文件
     *
     * @param bucketName  存储桶
     * @param objectName  文件对象
     * @param inputStream 文件流
     */
    public ObjectWriteResponse putObjectByStream(String bucketName, String objectName, InputStream inputStream) {
        try {
            PutObjectArgs args = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(objectName)
                    .stream(inputStream, inputStream.available(), -1)
                    .build();
            return minioClient.putObject(args);
        } catch (ErrorResponseException | InsufficientDataException | InternalException |
                InvalidKeyException | InvalidResponseException | IOException | NoSuchAlgorithmException |
                ServerException | XmlParserException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取⽂件外链
     *
     * @param bucketName bucket名称
     * @param objectName ⽂件名称
     * @param expires    过期时间 <=7
     */
    public String getObjectUrl(String bucketName, String objectName, Integer expires) {
        GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder()
                .method(Method.GET)
                .bucket(bucketName)
                .object(objectName)
                .expiry(expires)    // 单位:秒
                .build();

        try {
            return minioClient.getPresignedObjectUrl(args);
        } catch (ErrorResponseException | InsufficientDataException | InternalException |
                InvalidResponseException | InvalidKeyException | NoSuchAlgorithmException |
                IOException | XmlParserException | ServerException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 获取⽂件外链
     *
     * @param bucketName bucket名称
     * @param objectName ⽂件名称
     * @param duration 过期时间
     * @param unit  过期时间的单位
     */
    public String getObjectUrl(String bucketName, String objectName, int duration, TimeUnit unit) {
        GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder()
                .method(Method.GET)
                .bucket(bucketName)
                .object(objectName)
                .expiry(duration, unit)
                .build();

        try {
            return minioClient.getPresignedObjectUrl(args);
        } catch (ErrorResponseException | InsufficientDataException | InternalException |
                InvalidResponseException | InvalidKeyException | NoSuchAlgorithmException |
                IOException | XmlParserException | ServerException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 创建文件夹或目录
     *
     * @param bucketName 存储桶
     * @param objectName 目录路径
     */
    public ObjectWriteResponse putDirObject(String bucketName, String objectName) {
        PutObjectArgs args = PutObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .stream(new ByteArrayInputStream(new byte[]{}), 0, -1)
                .build();
        try {
            return minioClient.putObject(args);
        } catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidKeyException |
                InvalidResponseException | IOException | NoSuchAlgorithmException | ServerException | XmlParserException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 判断文件是否存在
     *
     * @param bucketName 存储桶
     * @param objectName 对象
     * @return true:存在
     */
    public boolean doesObjectExist(String bucketName, String objectName) {
        StatObjectArgs args = StatObjectArgs.builder().bucket(bucketName).object(objectName).build();
        try {
            minioClient.statObject(args);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 判断文件夹是否存在
     *
     * @param bucketName 存储桶
     * @param objectName 文件夹名称(去掉/)
     * @return true:存在
     */
    public boolean doesFolderExist(String bucketName, String objectName) {
        ListObjectsArgs args = ListObjectsArgs.builder()
                .bucket(bucketName)
                .prefix(objectName)
                .recursive(false)
                .build();
        boolean exist = false;
        try {
            Iterable<Result<Item>> results = minioClient.listObjects(args);
            for (Result<Item> result : results) {
                Item item = result.get();
                if (!item.isDir())
                    continue;
                if (objectName.equals(item.objectName())) {
                    exist = true;
                }
            }
        } catch (Exception e) {
            exist = false;
        }
        return exist;
    }

    /**
     * 获取文件信息
     *
     * @param bucketName bucket名称
     * @param objectName ⽂件名称
     * @throws Exception https://docs.minio.io/cn/java-client-api-reference.html#statObject
     */
    public StatObjectResponse getObjectInfo(String bucketName, String objectName) {
        StatObjectArgs args = StatObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .build();
        try {
            return minioClient.statObject(args);
        } catch (ErrorResponseException | InsufficientDataException | InternalException |
                InvalidKeyException | InvalidResponseException | IOException | NoSuchAlgorithmException |
                ServerException | XmlParserException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 删除文件
     *
     * @param bucketName bucket名称
     * @param objectName ⽂件名称
     * @throws Exception https://docs.minio.io/cn/java-client-apireference.html#removeObject
     */
    public void removeObject(String bucketName, String objectName) {
        RemoveObjectArgs args = RemoveObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .build();
        try {
            minioClient.removeObject(args);
        } catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidKeyException | InvalidResponseException | IOException | NoSuchAlgorithmException | ServerException | XmlParserException e) {
            e.printStackTrace();
        }
    }
}
  • 27
    点赞
  • 26
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MinIO文件服务器是一个轻量级的对象存储服务器,可以在本地计算机或云环境中运行。你可以使用MinIO来存储和访问大量的数据。根据不同的操作系统和环境,安装和配置MinIO有几种不同的方法。 对于Windows操作系统,你可以在Windows PowerShell中执行以下命令来安装和配置MinIO: setx MINIO_ROOT_USER admin Invoke-WebRequest -Uri "https://dl.min.io/server/minio/release/windows-amd64/minio.exe" -OutFile "C:\minio.exe" setx MINIO_ROOT_PASSWORD password C:\minio.exe server F:\Data --console-address ":9001" 对于Linux操作系统,你可以在命令行中执行以下命令来安装和配置MinIO: wget https://dl.min.io/server/minio/release/linux-amd64/minio chmod +x minio MINIO_ROOT_USER=admin MINIO_ROOT_PASSWORD=password ./minio server ./minio --console-address ":9001" 对于MacOS操作系统,你可以在命令行中执行以下命令来安装和配置MinIO: wget https://dl.min.io/server/minio/release/darwin-amd64/minio chmod +x minio MINIO_ROOT_USER=admin MINIO_ROOT_PASSWORD=password ./minio server F:\Data --console-address ":9001" 另一种推荐的方法是使用Docker来安装和配置MinIO。你可以使用以下命令来下载并启动MinIO容器: docker-compose up -d 这是一个示例的docker-compose.yml文件的内容: version: '3' services: minio: image: minio/minio hostname: "minio" ports: - "9000:9000" # api 端口 - "9001:9001" # 控制台端口 environment: MINIO_ACCESS_KEY: admin #管理后台用户名 MINIO_SECRET_KEY: password #管理后台密码,最小8个字符 volumes: - /home/deepsoft/minio/data:/data #映射当前目录下的data目录至容器内/data目录 - /home/deepsoft/minio/config:/root/.minio/ #映射配置目录 command: server --console-address ':9001' /data #指定容器中的目录 /data privileged: true restart: always logging: options: max-size: "50M" # 最大文件上传限制 max-file: "10" driver: json-file networks: - minio 这些是安装和配置MinIO文件服务器的不同方法和步骤,你可以根据你的操作系统和环境选择合适的方法来进行安装。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [MinIO分布式文件服务器搭建与入门](https://blog.csdn.net/lemon_TT/article/details/124675675)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] - *2* [第03讲:MinIO分布式文件服务器](https://blog.csdn.net/qzc70919700/article/details/129988299)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值