java 集成MinIo

2023-11-19

1.引入maven包(注意jar包冲突)

<!--minio依赖开始-->
        <dependency>
            <groupId>io.minio</groupId>
            <artifactId>minio</artifactId>
            <version>8.4.3</version>
            <exclusions>
                <exclusion>
                    <groupId>com.fasterxml.jackson.core</groupId>
                    <artifactId>jackson-core</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.fasterxml.jackson.core</groupId>
                    <artifactId>jackson-databind</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>com.google.guava</groupId>
                    <artifactId>guava</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!--minio依赖结束-->

<!--需要依赖的其他包-->
<dependency>
   <groupId>com.squareup.okhttp3</groupId>
   <artifactId>okhttp</artifactId>
   <version>4.9.0</version>
</dependency>

2.测试类(建新桶一定赋权)

package com.example.demo;

import io.minio.*;
import io.minio.errors.MinioException;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class JavaMinIOUtil {
        public static void main(String[] args)
                throws IOException, NoSuchAlgorithmException, InvalidKeyException {
            try {
                // Create a minioClient with the MinIO server playground, its access key and secret key.
                MinioClient minioClient =
                        MinioClient.builder()
                                .endpoint("地址")
                                .credentials("用户名", "密码")
                                .build();

                // Make 'asiatrip' bucket if not exist.
                boolean found =
                        minioClient.bucketExists(BucketExistsArgs.builder().bucket("group1").build());
                if (!found) {
                    // Make a new bucket called 'asiatrip'.
                    minioClient.makeBucket(MakeBucketArgs.builder().bucket("group1").build());
                    minioClient.setBucketPolicy(
                            SetBucketPolicyArgs.builder().bucket("group1").config("这里是赋权").build());
                } else {
                    System.out.println("Bucket 'asiatrip' already exists.");
                }

                // Upload '/home/user/Photos/asiaphotos.zip' as object name 'asiaphotos-2015.zip' to bucket
                // 'asiatrip'.
                minioClient.uploadObject(
                        UploadObjectArgs.builder()
                                .bucket("group1")
                                .object("test/bm.jpg")
                                .filename("C:\\img\\苞米.jpg")
                                .build());
            } catch (MinioException e) {
                System.out.println("Error occurred: " + e);
                System.out.println("HTTP trace: " + e.httpTrace());
            }
        }
    }

3.工具类

package com.neixunbao.platform.minio;

import io.minio.*;
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 org.apache.http.entity.ContentType;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.neixunbao.platform.image.util.FileUtil.readInputStream;

/**
 * 功能描述 文件服务器工具类
 *
 * @author:
 * @date:
 */
@Component
public class MinIOUtil {
    //MinIO的API请求地址
    private final static String ENDPOINT = "http://127.0.0.1:9090";
    //用户名
    private final static String USERNAME = "admin";
    //密码
    private final static String PASSWORD = "1111";
    //桶名称
    private final static String BUCKETNAME = "group1";

    //回显路径
    public final static String BASEURL = "http://127.0.0.1:9090/group1/";

    //单例加载
    private final static MinioClient minioClient = MinioClient.builder().endpoint(ENDPOINT).credentials(USERNAME, PASSWORD).build();

   /**
     * 查看存储bucket是否存在
     * @return boolean
     */
    public Boolean bucketExists() {
        Boolean found;
        try {
            found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(BUCKETNAME).build());
            minioClient.setBucketPolicy(
                    SetBucketPolicyArgs.builder().bucket(BUCKETNAME).config("{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:ListBucketMultipartUploads\",\"s3:GetBucketLocation\",\"s3:ListBucket\"],\"Resource\":[\"arn:aws:s3:::group1\"]},{\"Effect\":\"Allow\",\"Principal\":{\"AWS\":[\"*\"]},\"Action\":[\"s3:AbortMultipartUpload\",\"s3:DeleteObject\",\"s3:GetObject\",\"s3:ListMultipartUploadParts\",\"s3:PutObject\"],\"Resource\":[\"arn:aws:s3:::group1/*\"]}]}").build());
        } catch (Exception e) {
            //e.printStackTrace();
            return false;
        }
        return found;
    }

    /**
     * 创建存储bucket
     * @return Boolean
     */
    public Boolean makeBucket(String bucketName) {
        try {
            minioClient.makeBucket(MakeBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    /**
     * 删除存储bucket
     * @return Boolean
     */
    public Boolean removeBucket(String bucketName) {
        try {
            minioClient.removeBucket(RemoveBucketArgs.builder()
                    .bucket(bucketName)
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }
    /**
     * 获取全部bucket
     */
    public List<Bucket> getAllBuckets() {
        try {
            return minioClient.listBuckets();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 文件上传
     * @param file 文件
     * @return Boolean
     */
    public static String upload(MultipartFile file) {
        try {
            //MultipartFile转InputStream
            byte [] byteArr=file.getBytes();
            InputStream inputStream = new ByteArrayInputStream(byteArr);

            //获取文件名称
            String filename = file.getOriginalFilename();
            String prefix = filename.substring(filename.lastIndexOf(".") + 1);//后缀
            //根据当前时间生成文件夹
            Calendar calendar = Calendar.getInstance();
            Date time = calendar.getTime();
            // 2. 格式化系统时间--- 这里的时间格式可以根据自己的需要进行改变
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String buckfilename = format.format(time);

            String uuid= UUID.randomUUID().toString().replace("-","");//customer_YYYYMMDDHHMM
            String fileName = buckfilename+"/"+uuid+"."+prefix; //文件全路径

            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(BUCKETNAME).object(fileName)
                    .stream(inputStream,file.getSize(),-1).contentType(file.getContentType()).build();
            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);
            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    /**
     * 上传文件---直接传file
     *
     * @return
     */
    public static String upload(byte data[],String fileName) {
//        File file = byte2File(data,"D:\\lsfile",fileName);
        try {
//            MultipartFile multipartFile = getMultipartFile(file);
//            byte [] byteArr=multipartFile.getBytes();
            InputStream inputStream = new ByteArrayInputStream(data);
            //获取文件名称
            String prefix = fileName.substring(fileName.lastIndexOf(".") + 1);//后缀
            //根据当前时间生成文件夹
            Calendar calendar = Calendar.getInstance();
            Date time = calendar.getTime();
            // 2. 格式化系统时间--- 这里的时间格式可以根据自己的需要进行改变
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String buckfilename = format.format(time);

            String uuid= UUID.randomUUID().toString().replace("-","");//customer_YYYYMMDDHHMM
            fileName = buckfilename+"/"+uuid+"."+prefix; //文件全路径

            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(BUCKETNAME).object(fileName)
                    .stream(inputStream,data.length,-1).contentType("image/"+prefix).build();
            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);
            return fileName;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
        }
        return "";
    }

    /**
     * 上传文件---直接传file
     *
     * @return
     */
    public static String upload(File file) {
        try {
            MultipartFile multipartFile = getMultipartFile(file);
            byte [] byteArr=multipartFile.getBytes();
            InputStream inputStream = new ByteArrayInputStream(byteArr);
            //获取文件名称
            String filename = multipartFile.getOriginalFilename();
            String prefix = filename.substring(filename.lastIndexOf(".") + 1);//后缀
            //根据当前时间生成文件夹
            Calendar calendar = Calendar.getInstance();
            Date time = calendar.getTime();
            // 2. 格式化系统时间--- 这里的时间格式可以根据自己的需要进行改变
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            String buckfilename = format.format(time);

            String uuid= UUID.randomUUID().toString().replace("-","");//customer_YYYYMMDDHHMM
            filename = buckfilename+"/"+uuid+"."+prefix; //文件全路径

            PutObjectArgs objectArgs = PutObjectArgs.builder().bucket(BUCKETNAME).object(filename)
                    .stream(inputStream,multipartFile.getSize(),-1).contentType(multipartFile.getContentType()).build();
            //文件名称相同会覆盖
            minioClient.putObject(objectArgs);
            return filename;
        } catch (Exception e) {
            e.printStackTrace();
        }
            return "";
        }

    /**
     * 预览图片
     * @param fileName
     * @return
     */
    public String preview(String fileName){
        // 查看文件地址
        GetPresignedObjectUrlArgs build = new GetPresignedObjectUrlArgs().builder().bucket(BUCKETNAME).object(fileName).method(Method.GET).build();
        try {
            String url = minioClient.getPresignedObjectUrl(build);
            return url;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 文件下载
     * @param fileName 文件名称
     * @param res response
     * @return Boolean
     */
    public void download(String fileName, HttpServletResponse res) {
        GetObjectArgs objectArgs = GetObjectArgs.builder().bucket(BUCKETNAME)
                .object(fileName).build();
        try (GetObjectResponse response = minioClient.getObject(objectArgs)){
            byte[] buf = new byte[1024];
            int len;
            try (FastByteArrayOutputStream os = new FastByteArrayOutputStream()){
                while ((len=response.read(buf))!=-1){
                    os.write(buf,0,len);
                }
                os.flush();
                byte[] bytes = os.toByteArray();
                res.setCharacterEncoding("utf-8");
                //设置强制下载不打开
                //res.setContentType("application/force-download");
                res.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                try (ServletOutputStream stream = res.getOutputStream()){
                    stream.write(bytes);
                    stream.flush();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 查看文件对象
     * @return 存储bucket内文件对象信息
     */
    public List<Item> listObjects() {
        Iterable<Result<Item>> results = minioClient.listObjects(
                ListObjectsArgs.builder().bucket(BUCKETNAME).build());
        List<Item> items = new ArrayList<>();
        try {
            for (Result<Item> result : results) {
                items.add(result.get());
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return items;
    }

    /**
     * 删除
     * @param fileName
     * @return
     * @throws Exception
     */
    public static boolean remove(String fileName){
        try {
            minioClient.removeObject( RemoveObjectArgs.builder().bucket(BUCKETNAME).object(fileName).build());
        }catch (Exception e){
            return false;
        }
        return true;
    }

    /**
     * 批量删除文件对象(没测试)
     * @param objects 对象名称集合
     */
    public Iterable<Result<DeleteError>> removeObjects(List<String> objects) {
        List<DeleteObject> dos = objects.stream().map(e -> new DeleteObject(e)).collect(Collectors.toList());
        Iterable<Result<DeleteError>> results = minioClient.removeObjects(RemoveObjectsArgs.builder().bucket(BUCKETNAME).objects(dos).build());
        return results;
    }
    public static void dfsdelete(String path) {
        File file=new File(path);
        if(file.isFile()) {//如果此file对象是文件的话,直接删除
            file.delete();
            return;
        }
        //当 file是文件夹的话,先得到文件夹下对应文件的string数组 ,递归调用本身,实现深度优先删除
        String [] list=file.list();
        for (int i = 0; i < list.length; i++) {
            dfsdelete(path+File.separator+list[i]);

        }//当把文件夹内所有文件删完后,此文件夹已然是一个空文件夹,可以使用delete()直接删除
        file.delete();
        return;
    }


    /**
     * 得到文件流
     * @param url  网络图片URL地址
     * @return
     */
    public static byte[] getFileStream(String url){
        try {
            URL httpUrl = new URL(url);
            HttpURLConnection conn = (HttpURLConnection)httpUrl.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
            byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
            return btImg;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 从输入流中获取数据
     * @param inStream 输入流
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len=inStream.read(buffer)) != -1 ){
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

    /**
     * file转byte
     */
    public static byte[] file2byte(File file){
        byte[] buffer = null;
        try{
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1)
            {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }
        catch (IOException e){
            e.printStackTrace();
        }
        return buffer;
    }

    /**
     * byte 转file
     */
    public static File byte2File(byte[] buf, String filePath, String fileName){
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try{
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory()){
                dir.mkdirs();
            }
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(buf);
        }catch (Exception e){
            e.printStackTrace();
        }
        finally{
            if (bos != null){
                try{
                    bos.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
            if (fos != null){
                try{
                    fos.close();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }
        return file;
    }
    /**
     * multipartFile转File
     **/
    public static File multipartFile2File(MultipartFile multipartFile){
        File file = null;
        if (multipartFile != null){
            try {
                file=File.createTempFile("tmp", null);
                multipartFile.transferTo(file);
                System.gc();
                file.deleteOnExit();
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return file;
    }
    /**
     * File转multipartFile
     **/
    public static MultipartFile getMultipartFile(File file) {
        DiskFileItem item = new DiskFileItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName()
                , (int)file.length()
                , file.getParentFile());
        try {
            OutputStream os = item.getOutputStream();
            os.write(FileUtils.readFileToByteArray(file));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new CommonsMultipartFile(item);
    }

//    //上传文件,返回路径
//    public Object upload(HashMap<String, Object> paramMap) {
//        MultipartFile file=(MultipartFile)paramMap.get("file");
//        if (file.isEmpty() || file.getSize() == 0) {
//            return "文件为空";
//        }
//        try {
//            if (!this.bucketExists()) {
//                this.makeBucket("group1");
//            }
//            InputStream inputStream = file.getInputStream();
//            String fileName = file.getOriginalFilename();
//
//            String newName = UUID.randomUUID().toString().replaceAll("-", "")
//                    + fileName.substring(fileName.lastIndexOf("."));
//
//            this.upload( newName,file, inputStream);
//            inputStream.close();
//            String fileUrl = this.preview(newName);
//            String fileUrlNew=fileUrl.substring(0, fileUrl.indexOf("?"));
//            JSONObject jsonObject=new JSONObject();
//            jsonObject.put("url",fileUrlNew);
//            return jsonObject.toJSONString();
//        } catch (Exception e) {
//            e.printStackTrace();
//            return "上传失败";
//        }
//    }
}

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

java 集成MinIo 的相关文章

随机推荐

  • 空指针异常:trim(),isEmpty()造成

    Trim 对空的再使用会报空指针异常 空字符串是 会创建一个对象 内容是 有内存空间 而null 不会创建对象 没有内存空间 长度为0 这时候再用isEmpty 的会报 空指针异常 尽量使用 null if role getId null
  • 性能测试知多少

    目录 1 性能测试基本理论 1 1 性能测试概念 1 1 1 什么是性能 1 1 2 什么是性能测试 1 2 性能测试基本内容 1 2 1 性能测试 1 2 2 负载测试 1 2 3 压力测试 1 2 4 稳定性测试 1 3 性能测试常用名
  • 二叉树的各种操作函数

    include source h 满与空的问题 计算个数时 判断rear和front的大小1 2 空一个 void InitQueue Queue u u front 0 u rear 0 int sizeQue Queue u int s
  • 测试中常说的持续集成是什么?有什么好处?

    一 持续集成流程 正式接收开发转过来的包之前 先从 svn 上下载代码 给它做次静态代码检查 然后编译打包 可以在开发的服务器或者自己的服务器运行单元测试文件 单元测试后 没用什么大的 bug 再部署到测试环境中 测试环境部署完成后先做冒烟
  • 15 个高级 Java 多线程面试题及回答

    在任何Java面试当中多线程和并发方面的问题都是必不可少的一部分 如果你想获得任何股票投资银行的前台资讯职位 那么你应该准备很多关于多线程的问题 在投资银行业务中多线程和并发是一个非常受欢迎的话题 特别是电子交易发展方面相关的 他们会问面试
  • 【新手基础】-域内域信息搜集

    查看当前权限 Whomai 本地普通用户 win 2008 user 本地管理员用户 win7 x64 test administrator 域内用户 hacker administrator 获取域id sid 域id是唯一id Whoa
  • 数据仓库进阶 《阿里大数据之路》第二篇 数据模型篇 (完整版)

    第8章 大数据领域建模综述 此文章为学习笔记 有兴趣的小伙伴可以根据以下指引获取更多 学习内容链接如下 视频 一起啃书 阿里大数据之路数据仓库建模基础理论研读 已完结 哔哩哔哩 bilibili 书籍 阿里大数据之路 8 1 为什么需要数据
  • 【C/C++】浮点数的比较

    本文为 C C 学习总结 讲解浮点数的比较 浮点数经过大量运算后会损失精度 对比较操作带来较大困扰 因为 C 中的 操作需要完全相同时才能判定为 true 我们引入一个极小数 eps 修正误差 比较运算符 若一个数 a 落在 b eps b
  • 网络环境下促进有效学习发生的策略

    1 构建良好的网络学习环境 学习者在网络中的学习 必须在一定的 适合学习的环境中进行 构建和谐和 宽松的学习环境是激发学习者有效学习的前提 在这样的环境中 应该有学习者学 习所需要的一些网络资源 如各种教学网站 电子期刊等 也需要有一定的认
  • nginx之proxy_pass代理后端https请求

    本文转载自 https my oschina net foreverich blog 1517128 前言本文解释了怎么对nginx和后端服务器组或代理服务器进行加密http通信 内容提纲前提条件获取SSL服务端证书获取SSL客户端证书配置
  • MySQL Error Code: 2013. Lost connection to MySQL server during query解决

    如果你出现了这个问题 先尝试判断你是哪种情况 你的SQL语句需要执行很久 超过默认的时长 gt 方案1 你的SQL语句很简单 但就是执行不了 gt 方案2 解决方法1 尝试打开设置调整超时时间后重试 解决方法2 如果你在尝试修改空表都发生了
  • 2. Java枚举(enum)

    Java枚举是一个特殊的类 一般表示一组常量 使用enum关键字来定义 各个常量使用逗号 来分割 实例 public enum BizErrorInfo USER NOT FOUND codeValue 1004 message 用户不存在
  • Springboot +mybatis-plus 实现公共字段自动填充

    本文讲述了在SpringBoot 中使用Mybatis Plus如何实现一个自动填充功能 目录 一 应用场景 二 代码实现步骤 1 建数据库表 t user 2 创建spring boot项目集成mybatis plus实现字段自动填充 2
  • 少儿机器人编程主要使用的语言有啥

    少儿机器人编程主要使用的语言 说起孩子的学习 想必家长们都是非常的有发言权的 很多的家长在培养孩子的学习方面也可以说相当的耐心的 他们会给孩子选择一些能够有利于孩子成长的课程 就拿现在很多的家长想要孩子去学习机器人编程的课程来说 有的家长对
  • PHP开源大全

    WordPress PHP开源 博客Blog WordPress是最热门的开源个人信息发布系统 Blog 之一 基于PHP MySQL构建 WordPress提供的功能包括 1 文章发布 分类 归档 2 提供文章 评论 分类等多种形式的RS
  • MySQL数据库数据导出出现1290(secure_file_priv)错误解决方法

    目录 解决方案 测试效果 解决方案 secure file priv是用来限制mysql数据库导出的位置 目录 算是一直安全保护系统 我们可以去通过show variables like secure 这个指令去查看secure file
  • 2021-05-08记录一次最新版小红书逆向细节

    预备工具 ida7 5 piexl 手机 jadx jeb 某书是有TracerPid反调试 先过反调试 这有两个方法 1 Frida hook fopen 过滤 2 修改安卓源码去掉TracerPid 1 Frida hook脚本 fun
  • Python入门到实战(十一)无监督学习、KMeans、KNN、实现图像分割、监督学习VS无监督学习

    Python入门到实战 十一 无监督学习 KMeans KNN 实现图像分割 监督学习VS无监督学习 无监督学习unsupervised learning 特点 应用 K均值聚类 核心流程 核心公式 KMeans VS KNN 实战 KMe
  • 深度遍历 和 广度遍历

    深度dfs 用到了递归 先把根节点 输出根节点 然后遍历根节点的孩子 const fun1 root gt console log root val root children forEach fun1 fun1 tree 广度遍历 每次遍
  • java 集成MinIo

    1 引入maven包 注意jar包冲突