编程语言
首页 > 编程语言> > Java(spring boot)实现操作minio(最新版本minio)

Java(spring boot)实现操作minio(最新版本minio)

作者:互联网

1. 在pom文件中,添加依赖:

<dependency>
	<groupId>io.minio</groupId>
	<artifactId>minio</artifactId>
	<version>7.0.2</version>
</dependency>

2. 在yml文件中添加minio的配置信息:

minio:
  endpoint: http://192.168.1.55:9000
  accessKey: 1777QN2GK9S6N02G83NK
  secretKey: 6gMzG26973fXJfKxEOSxaUTrFdy3+QtSggdprESJ
  bucketName: test

3. 创建minio的配置文件:

package com.common.properties;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * minio配置信息
 * admin2021/9/6 16:57
 */
@Component
public class MinioProperties {

    public static String endpoint;

    public static String accessKey;

    public static String secretKey;

    public static String bucketName;

    @Value("${minio.endpoint}")
    public void setEndpoint(String endpoint) {
        MinioProperties.endpoint = endpoint;
    }

    @Value("${minio.accessKey}")
    public void setAccessKey(String accessKey) {
        MinioProperties.accessKey = accessKey;
    }

    @Value("${minio.secretKey}")
    public void setSecretKey(String secretKey) {
        MinioProperties.secretKey = secretKey;
    }

    @Value("${minio.bucketName}")
    public void setBucketName(String bucketName) {
        MinioProperties.bucketName = bucketName;
    }

}

4. 编写minio工具类:

package com.common.utils;

import com.common.properties.MinioProperties;
import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLDecoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * minio文件上传工具类
 */
@Slf4j
public class MinioUtil {

    private static String endpoint;

    private static String accessKey;

    private static String secretKey;

    private static String bucketName;

    static {
        endpoint = MinioProperties.endpoint;
        accessKey = MinioProperties.accessKey;
        secretKey = MinioProperties.secretKey;
        bucketName = MinioProperties.bucketName;
    }

    private static MinioClient minioClient = null;

    /**
     * 上传文件
     *
     * @param file 文件
     * @return 文件链接地址
     */
    public static Object upload(MultipartFile file) {
        String file_url = "";
        try {
            initMinio(endpoint, accessKey, secretKey);
            // 检查存储桶是否已经存在
            if (minioClient.bucketExists(bucketName)) {
                log.info("Bucket already exists.");
            } else {
                // 创建一个名为ota的存储桶
                minioClient.makeBucket(bucketName);
                log.info("create a new bucket.");
            }
            InputStream stream = file.getInputStream();
            // 获取文件名
            String orgName = file.getOriginalFilename();
            if ("".equals(orgName)) {
                orgName = file.getName();
            }
            orgName = getFileName(orgName);
            String objectName = "/" + orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));

            // 使用putObject上传一个本地文件到存储桶中。
            minioClient.putObject(bucketName, objectName, stream, new PutObjectOptions(stream.available(), -1));
            stream.close();
            file_url = minioClient.getObjectUrl(bucketName, objectName);
        } catch (IOException |
                RegionConflictException |
                InvalidResponseException |
                InvalidBucketNameException |
                InvalidKeyException |
                NoSuchAlgorithmException |
                XmlParserException |
                ErrorResponseException |
                InternalException |
                InsufficientDataException e) {
            log.error(e.getMessage(), e);
        }
        return file_url;
    }

    /**
     * 获取文件流
     */
    public static InputStream getMinioFile(String bucketName, String objectName) {
        InputStream inputStream = null;
        try {
            initMinio(endpoint, accessKey, secretKey);
            inputStream = minioClient.getObject(bucketName, objectName);
        } catch (Exception e) {
            log.info("文件获取失败" + e.getMessage());
        }
        return inputStream;
    }

    /**
     * 删除文件
     */
    public static void removeObject(String bucketName, String objectName) {
        try {
            initMinio(endpoint, accessKey, secretKey);
            minioClient.removeObject(bucketName, objectName);
        } catch (Exception e) {
            log.info("文件删除失败" + e.getMessage());
        }
    }

    /**
     * 获取文件外链
     */
    public static String getObjectURL(String bucketName, String objectName, Integer expires) {
        initMinio(endpoint, accessKey, secretKey);
        try {
            String url = minioClient.presignedGetObject(bucketName, objectName, expires);
            return URLDecoder.decode(url, "UTF-8");
        } catch (Exception e) {
            log.info("文件路径获取失败" + e.getMessage());
        }
        return null;
    }

    /**
     * 初始化客户端
     */
    private static void initMinio(String endpoint, String accessKey, String secretKey) {
        if (minioClient == null) {
            try {
                minioClient = new MinioClient(endpoint, accessKey, secretKey);
            } catch (InvalidEndpointException | InvalidPortException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 判断文件名是否带盘符,重新处理
     */
    private static String getFileName(String fileName) {
        //判断是否带有盘符信息
        // Check for Unix-style path
        int unixSep = fileName.lastIndexOf('/');
        // Check for Windows-style path
        int winSep = fileName.lastIndexOf('\\');
        // Cut off at latest possible point
        int pos = (winSep > unixSep ? winSep : unixSep);
        if (pos != -1) {
            // Any sort of path separator found...
            fileName = fileName.substring(pos + 1);
        }
        //替换上传文件名字的特殊字符
        fileName = fileName.replace("=", "").replace(",", "").replace("&", "").replace("#", "");
        return fileName;
    }


}

你的努力,终将成为你最有力的资本!

标签:Java,minio,spring,accessKey,secretKey,static,bucketName,String
来源: https://blog.csdn.net/yangkuo024/article/details/120142194