MinIO文件服务器的安装使用

什么是MinIO?

MinIO 是一款高性能、分布式的对象存储系统

MinIO提供高性能、S3兼容的对象存储

目录

一、安装步骤

1.1 连接服务器(此处为linux系统)

1.2 使用命令在root目录下创建minio文件夹,打开minio文件夹,下载minio

1.3 下载完成后会在当前目录下出现一个minio目录,为该文件添加可执行权限

1.4 创建minio文件存储目录及日志目录

1.5 在 /root/minio/目录下,新建一个run.sh并编辑以下内容,使用命令vim run.sh,然后将以下内容保存到run.sh。注:用户名和密码自己设置

1.6 为其赋予执行权限chmod u+x run.sh

1.7 启动minio并查看日志

1.8 访问其中的http://192.169.1.6:9002,使用5中配置的用户名密码登录

 1.9 创建Buckets(桶)

1.10 创建访问密钥并保存。注:springboot整合需要用到

 二、使用步骤

2.1 项目引入依赖

2.2 application.yml文件里配置minio。注:minio配置信息需改为自身的

2.3 创建minio配置类和工具类

2.4 创建一个数据表,用于保存上传到minio的文件的信息

2.5 使用代码自动生成器生成entity、controller、service、mapper。

2.6 创建minio上传、删除接口

2.7 封装上传返回数据MinioResponseDTO对象

2.8 测试


一、安装步骤

1.1 连接服务器(此处为linux系统)

1.2 使用命令在root目录下创建minio文件夹,打开minio文件夹,下载minio

cd
mkdir minio
cd minio
wget https://dl.min.io/server/minio/release/linux-amd64/minio

1.3 下载完成后会在当前目录下出现一个minio目录,为该文件添加可执行权限

chmod +x minio

1.4 创建minio文件存储目录及日志目录

# 创建minio文件存储目录及日志目录
mkdir -p /root/data/minio;
mkdir -p /root/logs/minio;

1.5 在 /root/minio/目录下,新建一个run.sh并编辑以下内容,使用命令vim run.sh,然后将以下内容保存到run.sh。注:用户名和密码自己设置

#!/bin/bash
export MINIO_ROOT_USER=minio-username
export MINIO_ROOT_PASSWORD=minio-password
# nohup启动服务 指定文件存放路径 /root/data 还有设置日志文件路径 /root/minio/log
nohup ./minio server --address :9002 --console-address :9001 /root/data/minio > /root/logs/minio/minio.log 2>&1 &

1.6 为其赋予执行权限chmod u+x run.sh

chmod u+x run.sh

1.7 启动minio并查看日志

# 启动minio服务
bash run.sh
# 查看日志
tail -200f /root/logs/minio/minio.log

 出现以下内容即安装成功

MinIO文件服务器的安装使用_第1张图片

1.8 访问其中的http://192.169.1.6:9002,使用5中配置的用户名密码登录

MinIO文件服务器的安装使用_第2张图片

 1.9 创建Buckets(桶)

MinIO文件服务器的安装使用_第3张图片

1.10 创建访问密钥并保存。注:springboot整合需要用到

MinIO文件服务器的安装使用_第4张图片

 二、使用步骤

2.1 项目引入依赖


   
       io.minio
       minio
       7.1.0
   

2.2 application.yml文件里配置minio。注:minio配置信息需改为自身的

minio:
  endpoint: http://192.168.1.6:9002
  # 安装步骤10中创建的访问密钥
  accessKey: ***************
  secretKey: ********************
  # 安装步骤9中创建的bckets名字
  bucketName: test
  secure: false
spring:
     mvc:
      hiddenmethod:
        filter:
          enabled: true
#        设置文件上传大小限制
  servlet:
    multipart:
      max-file-size: 100MB
      max-request-size: 150MB

2.3 创建minio配置类和工具类

配置类:

import io.minio.MinioClient;
import io.minio.errors.InvalidPortException;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

/**
 * @author Lannibar
 * @date: 2023-5-17
 * @Description minio配置
 */
@Configuration
@Component
@ConfigurationProperties(prefix = "minio")
@Data
public class MinioConfig {

    private String endpoint;

    private int port;

    private String accessKey;

    private String secretKey;

    private Boolean secure;

    private String bucketName;

    @Bean
    public MinioClient getMinioClient() throws InvalidPortException {
        MinioClient minioClient = MinioClient.builder().endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
        return minioClient;
    }

}

工具类:

package com.xiaomifeng.minio.util;
 
import io.minio.*;
import io.minio.errors.*;
import io.minio.http.Method;
import io.minio.messages.Bucket;
import io.minio.messages.DeleteError;
import io.minio.messages.DeleteObject;
import io.minio.messages.Item;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.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;
 
/**
 * MinIO 客户端工具类
 */
@Component
@Slf4j
public class MinioClientUtils {
 
    @Autowired
    private MinioClient minioClient;
 
    private static final int DEFAULT_EXPIRY_TIME = 7 * 24 * 3600;
 
    /**
     * 检查存储桶是否存在
     *
     * @param bucketName 存储桶名称
     * @return boolean
     */
    public boolean bucketExists(String bucketName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
        boolean flag = false;
        flag = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (flag) {
            return true;
        }
        return false;
    }
 
    /**
     * 创建存储桶
     *
     * @param bucketName 存储桶名称
     */
    public boolean makeBucket(String bucketName) throws IOException, InvalidKeyException, InvalidResponseException, RegionConflictException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
        boolean flag = bucketExists(bucketName);
        if (!flag) {
            minioClient.makeBucket(
                    MakeBucketArgs.builder()
                            .bucket(bucketName)
                            .build());
            return true;
        } else {
            return false;
        }
    }
 
    /**
     * 列出所有存储桶名称
     *
     * @return List
     */
    public List listBucketNames() throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
        List bucketList = listBuckets();
        List bucketListName = new ArrayList<>();
        for (Bucket bucket : bucketList) {
            bucketListName.add(bucket.name());
        }
        return bucketListName;
    }
 
    /**
     * 列出所有存储桶
     *
     * @return List
     */
    public List listBuckets() throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
        return minioClient.listBuckets();
    }
 
    /**
     * 删除存储桶
     *
     * @param bucketName 存储桶名称
     * @return boolean
     */
    public boolean removeBucket(String bucketName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            Iterable> myObjects = listObjects(bucketName);
            for (Result result : myObjects) {
                Item item = result.get();
                // 有对象文件,则删除失败
                if (item.size() > 0) {
                    return false;
                }
            }
            // 删除存储桶,注意,只有存储桶为空时才能删除成功。
            minioClient.removeBucket(RemoveBucketArgs.builder().bucket(bucketName).build());
            flag = bucketExists(bucketName);
            if (!flag) {
                return true;
            }
 
        }
        return false;
    }
 
    /**
     * 列出存储桶中的所有对象名称
     *
     * @param bucketName 存储桶名称
     * @return List
     */
    public List listObjectNames(String bucketName) throws XmlParserException, IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, InvalidBucketNameException, InsufficientDataException, InternalException {
        List listObjectNames = new ArrayList<>();
        boolean flag = bucketExists(bucketName);
        if (flag) {
            Iterable> myObjects = listObjects(bucketName);
            for (Result result : myObjects) {
                Item item = result.get();
                listObjectNames.add(item.objectName());
            }
        }
        return listObjectNames;
    }
 
    /**
     * 列出存储桶中的所有对象
     *
     * @param bucketName 存储桶名称
     * @return Iterable>
     */
    public Iterable> listObjects(String bucketName) throws XmlParserException, IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, InvalidBucketNameException, InsufficientDataException, InternalException {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            return minioClient.listObjects( ListObjectsArgs.builder().bucket(bucketName).build());
        }
        return null;
    }
 
    /**
     * 通过文件上传到对象
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @param fileName   File name
     * @return boolean
     */
    public boolean uploadObject(String bucketName, String objectName, String fileName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            minioClient.uploadObject(
                    UploadObjectArgs.builder()
                            .bucket(bucketName).object(objectName).filename(fileName).build());
            ObjectStat statObject = statObject(bucketName, objectName);
            if (statObject != null && statObject.length() > 0) {
                return true;
            }
        }
        return false;
 
    }
 
    /**
     * 文件上传
     *
     * @param bucketName 存储捅名称
     * @param multipartFile 文件
     * @param filename   文件名
     */
    public void putObject(String bucketName, MultipartFile multipartFile, String filename) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
        PutObjectOptions putObjectOptions = new PutObjectOptions(multipartFile.getSize(), PutObjectOptions.MIN_MULTIPART_SIZE);
        putObjectOptions.setContentType(multipartFile.getContentType());
        minioClient.putObject(
                PutObjectArgs.builder().bucket(bucketName).object(filename).stream(
                        multipartFile.getInputStream(), multipartFile.getSize(), -1).contentType(multipartFile.getContentType())
                        .build());
    }
 
    /**
     * 通过InputStream上传对象
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @param inputStream     要上传的流
     * @param contentType 上传的文件类型 例如 video/mp4  image/jpg
     * @return boolean
     */
    public boolean putObject(String bucketName, String objectName, InputStream inputStream,String contentType) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            minioClient.putObject(PutObjectArgs.builder().bucket(bucketName).object(objectName).stream(
                    //不清楚文件的大小时,可以传-1,10485760。如果知道大小也可以传入size,partsize。
                    inputStream,  -1, 10485760)
                    .contentType(contentType)
                    .build());
            ObjectStat statObject = statObject(bucketName, objectName);
            if (statObject != null && statObject.length() > 0) {
                return true;
            }
        }
        return false;
    }
 
    /**
     * 以流的形式获取一个文件对象
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @return InputStream
     */
    public InputStream getObject(String bucketName, String objectName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            ObjectStat statObject = statObject(bucketName, objectName);
            if (statObject != null && statObject.length() > 0) {
                InputStream stream = minioClient.getObject( GetObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .build());
                return stream;
            }
        }
        return null;
    }
 
    /**
     * 以流的形式获取一个文件对象(断点下载)
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @param offset     起始字节的位置
     * @param length     要读取的长度 (可选,如果无值则代表读到文件结尾)
     * @return InputStream
     */
    public InputStream getObject(String bucketName, String objectName, long offset, Long length) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            ObjectStat statObject = statObject(bucketName, objectName);
            if (statObject != null && statObject.length() > 0) {
                InputStream stream = minioClient.getObject(  GetObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .offset(1024L)
                        .length(4096L)
                        .build());
                return stream;
            }
        }
        return null;
    }
 
    /**
     * 下载并将文件保存到本地
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @param fileName   File name
     * @return boolean
     */
    public boolean downloadObject(String bucketName, String objectName, String fileName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            ObjectStat statObject = statObject(bucketName, objectName);
            if (statObject != null && statObject.length() > 0) {
                minioClient.downloadObject(DownloadObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .filename(fileName)
                        .build());
                return true;
            }
        }
        return false;
    }
 
    /**
     * 删除一个对象
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     */
    public boolean removeObject(String bucketName, String objectName) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(objectName).build());
            return true;
        }
        return false;
    }
 
    /**
     * 删除指定桶的多个文件对象,返回删除错误的对象列表,全部删除成功,返回空列表
     *
     * @param bucketName  存储桶名称
     * @param objectNames 含有要删除的多个object名称的迭代器对象
     * @return
     * eg:
     * List objects = new LinkedList<>();
     * objects.add(new DeleteObject("my-objectname1"));
     * objects.add(new DeleteObject("my-objectname2"));
     * objects.add(new DeleteObject("my-objectname3"));
     */
    public List removeObjects(String bucketName, List objectNames) throws IOException, InvalidKeyException, InvalidResponseException, InsufficientDataException, NoSuchAlgorithmException, ServerException, InternalException, XmlParserException, InvalidBucketNameException, ErrorResponseException {
        List deleteErrorNames = new ArrayList<>();
        boolean flag = bucketExists(bucketName);
        if (flag) {
            Iterable> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(bucketName).objects(objectNames).build());
            for (Result 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
     */
    public String getPresignedObjectUrl(String bucketName, String objectName, Integer expires) throws InvalidExpiresRangeException, IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
        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);
            }
            try {
                url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                        .method(Method.GET)
                        .bucket(bucketName)
                        .object(objectName)
                        .expiry(expires)//动态参数
                        //                       .expiry(24 * 60 * 60)//用秒来计算一天时间有效期
//                        .expiry(1, TimeUnit.DAYS)//按天传参
//                        .expiry(1, TimeUnit.HOURS)//按小时传参数
                        .build());
            } catch (ErrorResponseException | InsufficientDataException | InternalException | InvalidBucketNameException | InvalidExpiresRangeException | InvalidKeyException | InvalidResponseException | IOException | NoSuchAlgorithmException | ServerException | XmlParserException e) {
                e.printStackTrace();
            }
        }
        return url;
    }
 
    /**
     * 生成一个给HTTP PUT请求用的presigned URL。
     * 浏览器/移动端的客户端可以用这个URL进行上传,即使其所在的存储桶是私有的。这个presigned URL可以设置一个失效时间,默认值是7天。
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @param expires    失效时间(以秒为单位),默认是7天,不得大于七天
     * @return String
     */
    public String presignedPutObject(String bucketName, String objectName, Integer expires) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
        boolean flag = bucketExists(bucketName);
        String url = "";
        if (flag) {
            if (expires < 1 || expires > DEFAULT_EXPIRY_TIME) {
                try {
                    throw new InvalidExpiresRangeException(expires,
                            "expires must be in range of 1 to " + DEFAULT_EXPIRY_TIME);
                } catch (InvalidExpiresRangeException e) {
                    e.printStackTrace();
                }
            }
            try {
                url = minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                        .method(Method.PUT)
                        .bucket(bucketName)
                        .object(objectName)
                        .expiry(expires)//动态参数
                        //                       .expiry(24 * 60 * 60)//用秒来计算一天时间有效期
//                        .expiry(1, TimeUnit.DAYS)//按天传参
//                        .expiry(1, TimeUnit.HOURS)//按小时传参数
                        .build());
            } catch (ErrorResponseException | InsufficientDataException e) {
                e.printStackTrace();
            } catch (InternalException e) {
                log.error("InternalException",e);
            } catch (InvalidBucketNameException e) {
                log.error("InvalidBucketNameException",e);
            } catch (InvalidExpiresRangeException e) {
                log.error("InvalidExpiresRangeException",e);
            } catch (InvalidKeyException e) {
                log.error("InvalidKeyException",e);
            } catch (InvalidResponseException e) {
                log.error("InvalidResponseException",e);
            } catch (IOException e) {
                log.error("IOException",e);
            } catch (NoSuchAlgorithmException e) {
                log.error("NoSuchAlgorithmException",e);
            } catch (ServerException e) {
                log.error("ServerException",e);
            } catch (XmlParserException e) {
                log.error("XmlParserException",e);
            }
        }
        return url;
    }
 
    /**
     * 获取对象的元数据
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @return
     */
    public ObjectStat statObject(String bucketName, String objectName) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            ObjectStat statObject = null;
            try {
                statObject = minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(objectName).build());
            } catch (ErrorResponseException e) {
                log.error("ErrorResponseException",e);
            } catch (InsufficientDataException e) {
                log.error("ErrorResponseException",e);
                e.printStackTrace();
            } catch (InternalException e) {
                log.error("InternalException",e);
            } catch (InvalidBucketNameException e) {
                log.error("InvalidBucketNameException",e);
            } catch (InvalidKeyException e) {
                log.error("InvalidKeyException",e);
            } catch (InvalidResponseException e) {
                log.error("InvalidResponseException",e);
            } catch (IOException e) {
                log.error("IOException",e);
            } catch (NoSuchAlgorithmException e) {
                log.error("NoSuchAlgorithmException",e);
            } catch (ServerException e) {
                log.error("ServerException",e);
            } catch (XmlParserException e) {
                log.error("XmlParserException",e);
            }
            return statObject;
        }
        return null;
    }
 
    /**
     * 文件访问路径
     *
     * @param bucketName 存储桶名称
     * @param objectName 存储桶里的对象名称
     * @return String
     */
    public String getObjectUrl(String bucketName, String objectName) throws IOException, InvalidResponseException, InvalidKeyException, NoSuchAlgorithmException, ServerException, ErrorResponseException, XmlParserException, InvalidBucketNameException, InsufficientDataException, InternalException {
        boolean flag = bucketExists(bucketName);
        String url = "";
        if (flag) {
            try {
                url = minioClient.getObjectUrl(bucketName, objectName);
            } catch (ErrorResponseException e) {
                log.error("XmlParserException",e);
            } catch (InsufficientDataException e) {
                log.error("InsufficientDataException",e);
            } catch (InternalException e) {
                log.error("InternalException",e);
            } catch (InvalidBucketNameException e) {
                log.error("InvalidBucketNameException",e);
            } catch (InvalidKeyException e) {
                log.error("InvalidKeyException",e);
            } catch (InvalidResponseException e) {
                log.error("InvalidResponseException",e);
            } catch (IOException e) {
                log.error("IOException",e);
            } catch (NoSuchAlgorithmException e) {
                log.error("NoSuchAlgorithmException",e);
            } catch (ServerException e) {
                log.error("ServerException",e);
            } catch (XmlParserException e) {
                log.error("XmlParserException",e);
            }
        }
        return url;
    }
 
 
 
    public void downloadFile(String bucketName, String fileName, String originalName, HttpServletResponse response) {
        try {
 
            InputStream file = minioClient.getObject(GetObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .build());
            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) {
            log.error("ErrorResponseException",e);
        } catch (Exception e) {
            log.error("Exception",e);
        }
    }
}
 

2.4 创建一个数据表,用于保存上传到minio的文件的信息

CREATE TABLE `minio_file` (
  `id` bigint(20) NOT NULL COMMENT '文件id',
  `original_file_name` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '原始文件名称',
  `file_ext_name` varchar(15) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '文件拓展名',
  `file_size` bigint(20) DEFAULT NULL COMMENT '文件大小(单位:字节)',
  `file_name` varchar(35) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '存入minio时的文件名称',
  `mime` varchar(50) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '文件的content-type',
  `file_url` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '文件路径',
  `is_delete` tinyint(1) DEFAULT NULL COMMENT '是否删除 0 否 1 是',
  `create_by` varchar(25) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '创建者',
  `update_by` varchar(25) COLLATE utf8mb4_bin DEFAULT NULL COMMENT '更改者',
  `create_time` datetime DEFAULT NULL COMMENT '创建时间',
  `update_time` datetime DEFAULT NULL COMMENT '更新时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;

2.5 使用代码自动生成器生成entity、controller、service、mapper。

代码自动生成器文章地址:代码自动生成器_芒果味的戏子的博客-CSDN博客

2.6 创建minio上传、删除接口

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.config.oss.MinioConfig;
import org.jeecg.modules.dto.MinioResponseDTO;
import org.jeecg.modules.entity.MinioFile;
import org.jeecg.modules.service.MinioFileService;
import org.jeecg.modules.util.MinioClientUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;

/**
 * @author xiaomifeng1010
 * @version 1.0
 * @date: 2022/5/21 10:33
 * @Description  minio 文件处理(上传,下载,获取文件地址等)
 */
@Slf4j
@Api(tags = "文件处理模块")
@RestController
@CrossOrigin //处理跨域请求
@RequestMapping("/minioFile")
public class MinioFileController {

    @Resource
    private MinioClientUtils minioClientUtils;

    @Resource
    private MinioConfig minioConfig;

    @Autowired
    private MinioFileService minioFileService;

    @PostMapping(value = "/uploadFile")
    @ApiOperation(value = "上传文件,支持批量上传")
    @ApiImplicitParam(name = "files",value = "文件对象",dataType = "File")
    public Result uploadFile(@RequestParam("files") List files) {
        log.info(files.toString());
        if (CollectionUtils.isEmpty(files)){
            return Result.error("未选择文件!");
        }

        List MinioResponseDTOList=new ArrayList<>();
        for (MultipartFile file : files) {
            String originalFilename = file.getOriginalFilename();
//            获取文件拓展名
            String extName = FileUtil.extName(originalFilename);
            log.info("文件拓展名:"+extName);
//            生成新的文件名,存入到minio
            long millSeconds = Instant.now().toEpochMilli();
            String minioFileName=millSeconds+ RandomStringUtils.randomNumeric(12)+"."+extName;
            String contentType = file.getContentType();
            log.info("文件mime:{}",contentType);
//            返回文件大小,单位字节
            long size = file.getSize();
            log.info("文件大小:"+size);
            try {
                String bucketName = minioConfig.getBucketName();
                minioClientUtils.putObject(bucketName,file,minioFileName);
                String fileUrl = minioClientUtils.getObjectUrl(bucketName, minioFileName);
                MinioFile minioFile = new MinioFile();
                minioFile.setOriginalFileName(originalFilename);
                minioFile.setFileExtName(extName);
                minioFile.setFileName(minioFileName);
                minioFile.setFileSize(size);
                minioFile.setMime(contentType);
//                minioFile.setIsDelete(NumberUtils.INTEGER_ZERO);
                minioFile.setIsDelete(NumberUtils.INTEGER_ZERO == 0 ? false : true);

                minioFile.setFileUrl(fileUrl);
                boolean insert = minioFileService.save(minioFile);
                if (insert) {
                    MinioResponseDTO minioResponseDTO = new MinioResponseDTO();
                    minioResponseDTO.setFileId(minioFile.getId());
                    minioResponseDTO.setOriginalFileName(originalFilename);
                    minioResponseDTO.setFileUrl(fileUrl);
                    MinioResponseDTOList.add(minioResponseDTO);
                }

            } catch (Exception e) {
                log.error("上传文件出错:{}",e);
                return Result.error("上传文件出错");

            }
        }

        return Result.ok(MinioResponseDTOList);
    }

    /**
     * 删除文件
     * @param minioFileName 文件名称
     * @return
     */
    @ApiOperation(value = "删除文件" , notes = "删除文件")
    @RequestMapping(value = "/deleteMinioFile",method = RequestMethod.GET)
    public Result deleteMinioFile(@RequestParam String minioFileName){
        try {
            String bucketName = minioConfig.getBucketName();
            minioClientUtils.removeObject(bucketName,minioFileName);
            MinioFile minioFile = minioFileService.getOne(new QueryWrapper().eq("file_name",minioFileName));
            if (minioFile == null){
                log.error("文件不存在数据库表中!");
                return Result.error("文件不存在数据库表中!");
            }else{
                minioFileService.removeById(minioFile);
            }
        }catch (Exception e){
            log.error("删除文件失败!");
            return Result.error("删除文件失败!");
        }
        return Result.ok("删除文件成功");
    }
}

2.7 封装上传返回数据MinioResponseDTO对象

import io.swagger.annotations.ApiModelProperty;
import lombok.Data;

/**
 * 该实体主要用于封装用户提交的文件信息表单
 *
 * @author Lannibar
 * @since 2023-5-18
 */
@Data
public class MinioResponseDTO {

    @ApiModelProperty(value = "文件id")
    private Long fileId;

    @ApiModelProperty(value = "文件访问地址")
    private String fileUrl;

    @ApiModelProperty(value = "文件名")
    private String originalFileName;

}

2.8 测试

上传:

MinIO文件服务器的安装使用_第5张图片

数据库数据:

 使用返回的访问地址访问: 

MinIO文件服务器的安装使用_第6张图片

删除:

MinIO文件服务器的安装使用_第7张图片

至此,MinIO文件服务的安装和使用已完成。

文章仅供自身学习和参考。

你可能感兴趣的:(服务器,linux,运维)