SpringBoot + minio

文章介绍了如何在SpringBoot应用中集成Minio进行文件存储操作,包括初始化客户端、上传图片和删除文件的方法。通过定义Minio客户端,设置访问凭证,然后提供上传文件到指定桶的函数以及删除文件的函数,实现了简单的对象存储功能。
摘要由CSDN通过智能技术生成

前面文章中提到SpringBoot整合cos,minio其实也大同小异。

一、安装依赖

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

二、编写工具类

1.定义minio客户端和常量

private static MinioClient minioClient;
private static final String endpoint = "http://xxxxx.xxx:9000";
private static final String bucketName = "xxx";
private static final String accessKey = "xxxxxxxxxx";
private static final String secretKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
private static final String PREFIX = "diary/";

 2.初始化客户端

public static void createClient() {
    log.info(endpoint);
    try {
        minioClient = MinioClient
                .builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

3.上传图片方法

public static String uploadFile(MultipartFile file) throws Exception {

    createClient();
    InputStream inputStream = file.getInputStream();
    String contentType = file.getContentType();

    String originalPrefix = file.getOriginalFilename(); // 文件原始前缀名
    String originalSuffix = originalPrefix.substring(originalPrefix.lastIndexOf(".")); // 文件原始后缀名
    String fileNamePrefix = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); // 将上传时间作为新的文件前缀名
    Random random = new Random();
    String objectName = PREFIX + fileNamePrefix + "-" + random.nextInt(10000) + originalSuffix;
    try {
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .contentType(contentType)
                        .stream(inputStream, inputStream.available(), -1)
                        .build());
    } catch (Exception e) {
        e.printStackTrace();
    }

    return endpoint + "/" + bucketName + "/" + objectName + ";" + objectName;
}

4.删除文件方法

public static boolean removeFile(String objectName) throws Exception {
    try {
        minioClient.removeObject(
                RemoveObjectArgs.builder()
                        .bucket(bucketName)
                        .object(objectName)
                        .build());
    } catch (Exception e) {
        e.printStackTrace();
    }
    return true;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值