Minio配置与工具类

配置类

package com.woniu.friend.config;

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.context.annotation.Configuration;


@Data
@Configuration
/*加载yml文件中以minio开头的配置项*/
@ConfigurationProperties(prefix = "minio")
public class MinioConfig {
    /*会自动的对应配置项中对应的key*/
    private String endpoint;//minio.endpoint
    private String accessKey;
    private String secretKey;
    private Integer port;
    /*把官方提供的MinioClient客户端注册到IOC容器中*/
    @Bean
    public MinioClient getMinioClient() throws InvalidEndpointException,
            InvalidPortException {
        MinioClient minioClient = new MinioClient(getEndpoint(),
                getPort(), getAccessKey(), getSecretKey(), false);
        return minioClient;
    }


}

工具类

package com.woniu.friend.utils;

import io.minio.ObjectStat;
import io.minio.PutObjectOptions;
import io.minio.Result;
import io.minio.errors.*;
import io.minio.messages.DeleteError;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;


/**
 * minio客户端
 */
@Component
public class MinioClientUtil {

    @Value("${minio.bucketName}")
    private String bucketName;

    @Autowired
    private io.minio.MinioClient minioClient;
    private static final int DEFAULT_EXPIRY_TIME = 7 * 24 * 3600;

    /**
     * 检查存储桶是否存在
     */
    public boolean bucketExists(String bucketName) throws InvalidKeyException, ErrorResponseException,
            IllegalArgumentException, InsufficientDataException, InternalException, InvalidBucketNameException,
            InvalidResponseException, NoSuchAlgorithmException, XmlParserException, IOException {
        boolean flag = minioClient.bucketExists(this.bucketName);
        if (flag) return true;
        return false;
    }

    /**
     * 通过InputStream上传对象
     *
     * @param objectName 存储桶里的对象名称
     * @param stream     要上传的流 (文件的流)
     */
    public boolean putObject(String objectName, InputStream stream) throws Exception {

        //判断 桶是否存在
        boolean flag = bucketExists(bucketName);

        if (flag) {
            //往桶中添加数据   minioClient 进行添加

            /**
             *   参数1: 桶的名称
             *   参数2: 文件的名称
             *   参数3: 文件的流
             *   参数4: 添加的配置
             */
            minioClient.putObject(bucketName, objectName, stream, new PutObjectOptions(stream.available(), -1));
            ObjectStat statObject = statObject(objectName);
            if (statObject != null && statObject.length() > 0) {
                return true;
            }
        }
        return false;
    }

    /**
     * 删除一个对象
     * @param objectName 存储桶里的对象名称
     */
    public boolean removeObject(String objectName)throws Exception {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            minioClient.removeObject(bucketName, objectName);
            return true;
        }
        return false;
    }
    /**
     * 删除指定桶的多个文件对象,返回删除错误的对象列表,全部删除成功,返回空列表
     * @param objectNames 含有要删除的多个object名称的迭代器对象
     */
    public List<String> removeObject(List<String> objectNames) throws Exception {
        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;
    }

    /**
     * 获取对象的元数据
     * @param objectName 存储桶里的对象名称
     */
    public ObjectStat statObject(String objectName) throws Exception {
        boolean flag = bucketExists(bucketName);
        if (flag) {
            ObjectStat statObject = minioClient.statObject(bucketName, objectName);
            return statObject;
        }
        return null;
    }
    /**
     * 文件访问路径
     * @param objectName 存储桶里的对象名称
     */
    public String getObjectUrl(String objectName) throws Exception {
        boolean flag = bucketExists(bucketName);
        String url = "";
        if (flag) {
            url = minioClient.getObjectUrl(bucketName, objectName);
        }
        return url;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你可以使用以下的Python代码来创建一个Minio上传图片的工具类: ```python from minio import Minio from minio.error import ResponseError class MinioUploader: def __init__(self, endpoint, access_key, secret_key, bucket_name): self.endpoint = endpoint self.access_key = access_key self.secret_key = secret_key self.bucket_name = bucket_name def upload_image(self, file_path, object_name): try: minio_client = Minio(self.endpoint, access_key=self.access_key, secret_key=self.secret_key, secure=False) # 检查bucket是否存在,不存在则创建 if not minio_client.bucket_exists(self.bucket_name): minio_client.make_bucket(self.bucket_name) # 上传图片 minio_client.fput_object(self.bucket_name, object_name, file_path) return True, "Image uploaded successfully" except ResponseError as err: return False, f"Error uploading image: {err}" ``` 使用时,你需要提供Minio服务的endpoint、access_key、secret_key以及bucket_name。然后,你可以调用`upload_image`方法来上传图片。该方法接收两个参数:`file_path`表示本地图片文件的路径,`object_name`表示在Minio中保存的对象名称。 以下是一个使用示例: ```python minio_uploader = MinioUploader(endpoint='minio.example.com', access_key='your-access-key', secret_key='your-secret-key', bucket_name='your-bucket-name') success, message = minio_uploader.upload_image('/path/to/image.jpg', 'image.jpg') if success: print(message) else: print(f"Error: {message}") ``` 请确保已经安装了`minio`库,可以使用`pip install minio`来进行安装。此外,根据你实际的Minio配置,需要修改代码中的相关参数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值