在Linux系统下搭建和配置minio文件服务器+集成SpringBoot(二)

整合minio文件服务器在java代码中,讲述如何把minio整合进springboot中,特此说明,本篇只会贴出关于minio的关键代码,至于如何搭建springboot请个人百度。多的不说,少的不唠,上操作步骤。

1、添加pom.xml配置
<!--minio文件服务器-->
        <dependency>
            <groupId>io.minio</groupId>
            <artifactId>minio</artifactId>
            <version>8.2.0</version>
            <exclusions>
                <exclusion>
                    <groupId>com.squareup.okhttp3</groupId>
                    <artifactId>okhttp</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>3.12.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
2、添加yml配置文件
# minio 文件存储配置信息
minio:
  endpoint: http://127.0.0.1:9000
  accessKey: minioadmin
  secretKey: minioadmin
  bucketName: product

3、代码实现

3.1 实体配置

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

/**
 * minio 属性值
 */
@Data
@Component
@ConfigurationProperties(prefix = "minio")
public class MinioProp {
    /**
     * 端点
     */
    private String endpoint;
    /**
     * 用户名
     */
    private String accessKey;
    /**
     * 密码
     */
    private String secretKey;

    /**
     * 桶名称
     */
    private String bucketName;
}

3.2 核心配置类

import com.maven.maildemo.config.vo.MinioProp;
import io.minio.MinioClient;
import io.minio.errors.InvalidEndpointException;
import io.minio.errors.InvalidPortException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * minio 核心配置类
 */
@Configuration
@EnableConfigurationProperties(MinioProp.class)
public class MinioConfiguration {

    @Autowired
    private MinioProp minioProp;

    /**
     * 获取 MinioClient
     *
     * @return
     * @throws InvalidPortException
     * @throws InvalidEndpointException
     */
    @Bean
    public MinioClient minioClient() {
        MinioClient minioClient = MinioClient.builder()
            .endpoint(minioProp.getEndpoint())
            .credentials(minioProp.getAccessKey(), minioProp.getSecretKey())
            .build();
        return minioClient;
    }
}

3.3 配置工具类


import com.baomidou.mybatisplus.core.toolkit.Constants;
import io.minio.*;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 功能描述 minio工具类
 *
 * @author myc
 * @version 1.0
 * @className MinioUtil
 * @date 2022/3/8 14:40
 */
@Component
public class MinioUtil {

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

    @Autowired
    private MinioClient minioClient;

    /**
     * description: 判断bucket是否存在,不存在则创建
     *
     * @return: void
     * @author: myc
     * @time: 2021/8/25 10:20
     */
    public void existBucket(String name) {
        try {
            boolean exists = minioClient.bucketExists(BucketExistsArgs.builder().bucket(name).build());
            if (!exists) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(name).build());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 功能描述 上传文件
     *
     * @param multipartFile
     * @return {@link }
     * @author mayc
     * @date 2022/3/8
     */
    public void uploadFile(MultipartFile multipartFile) {
        String fileName = multipartFile.getOriginalFilename();
        String[] split = fileName.split("\\.");
        if (split.length > 1) {
            fileName = split[0] + "_" + System.currentTimeMillis() + "." + split[1];
        } else {
            fileName = fileName + System.currentTimeMillis();
        }
        InputStream in = null;
        try {
            in = multipartFile.getInputStream();
            minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(fileName)
                .stream(in, in.available(), -1)
                .contentType(multipartFile.getContentType())
                .build()
            );
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * description: 上传文件数组
     *
     * @param multipartFile
     * @return: java.lang.String
     * @author: myc
     * @time: 2021/8/25 10:44
     */
    public void uploadArray(MultipartFile[] multipartFile) {
        List<String> names = new ArrayList<>(multipartFile.length);
        for (MultipartFile file : multipartFile) {
            String fileName = file.getOriginalFilename();
            String[] split = fileName.split("\\.");
            if (split.length > 1) {
                fileName = split[0] + "_" + System.currentTimeMillis() + "." + split[1];
            } else {
                fileName = fileName + System.currentTimeMillis();
            }
            InputStream in = null;
            try {
                in = file.getInputStream();
                minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(fileName)
                    .stream(in, in.available(), -1)
                    .contentType(file.getContentType())
                    .build()
                );
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * description: 下载文件
     *
     * @param fileName
     * @return: org.springframework.http.ResponseEntity<byte [ ]>
     * @author: myc
     * @time: 2021/8/25 10:34
     */
    public byte[] download(String fileName) {
        byte[] bytes = null;
        InputStream in = null;
        ByteArrayOutputStream out = null;
        try {
            in = minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(fileName).build());
            out = new ByteArrayOutputStream();
            IOUtils.copy(in, out);
            //封装返回值
            bytes = out.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return bytes;
    }
}

3.3 控制器方法实现

package com.hzwq.transdi.provider.web.frontend.minio;

import com.hzwq.spring.boot.result.wrapper.annotation.ResultWrapper;
import com.hzwq.spring.boot.starter.swagger.annotation.ApiVersion;
import com.hzwq.transdi.provider.constant.SystemConstant;
import com.hzwq.transdi.provider.model.common.ResponseEntity;
import com.hzwq.transdi.provider.utils.MinioUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * minio文件管理,上传,下载文件
 *
 * @author MYC
 */
@RestController
@RequestMapping("/v1/minio/")
@ApiVersion
@ResultWrapper
@Slf4j
@Api(value = "minio文件管理", tags = {"minio文件管理"}, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class MinioController {

    @Autowired
    private MinioUtil minioUtil;

    /**
     * 上传文件
     *
     * @param file
     * @param request
     * @return
     */
    @PostMapping("/upload")
    @ApiOperation(value = "上传功能")
    public ResponseEntity upload(@RequestParam(value = "file") MultipartFile file, HttpServletRequest request) {
        ResponseEntity result = new ResponseEntity();
        if (file == null || file.getSize() == 0) {
            result = ResponseEntity.failure("上传文件不能为空");
        }
        try {
            minioUtil.uploadFile(file);
            result = ResponseEntity.success(SystemConstant.OPE_SUCCESS);
        } catch (Exception e) {
            log.error("上传失败", e);
            result = ResponseEntity.failure(SystemConstant.OPE_ERROR);
        }
        return result;
    }


    /**
     * 从minio服务器下载文件
     *
     * @param request
     * @param response
     * @param fileName
     */
    @PostMapping("/download")
    @ApiOperation(value = "下载功能")
    private ResponseEntity download(HttpServletRequest request, HttpServletResponse response, String fileName) {
        ResponseEntity result = new ResponseEntity();
        //获取文件对象 start原信息
        try {
            byte[] bytes = minioUtil.download(fileName);
            result = ResponseEntity.success(bytes, SystemConstant.OPE_SUCCESS);
        } catch (Exception e) {
            log.error("下载失败", e);
            result = ResponseEntity.failure(SystemConstant.OPE_ERROR);
        }
        return result;
    }

}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值