SpringBoot整合Minio

SpringBoot整合Minio

  1. 进入Minio官网,下载对应的Minio版本

    image-20221227142449024

    官网安装文档

    image-20221227143012393

  2. 下载完成之后,启动(windows版)

    minio.exe server D:\minio\server
    

    image-20221227143105861

    minio.exe server:启动服务

    D:\minio\server:设置上传图片存储路径

    API:上传图片链接(端口默认9000)

    RootUser:账号

    RootPass:密码

    Console:控制台地址

  3. 访问控制台地址:http://192.168.1.15:50932 进入控制台

    image-20221227143720582

  4. 创建存储桶

    image-20221227143845517

  5. 引入依赖

    <!--minio-->
            <dependency>
                <groupId>io.minio</groupId>
                <artifactId>minio</artifactId>
                <version>8.0.3</version>
            </dependency>
    
  6. yml配置

    server:
      port: 8099
    spring:
      # 配置文件上传大小限制
      servlet:
        multipart:
          max-file-size: 200MB
          max-request-size: 200MB
    minio:
    #文件上传接口
      endpoint: http://127.0.0.1:9000
      accessKey: minioadmin
      secretKey: minioadmin
      #存储通名称
      bucketName: img
    
    
  7. 配置类(注册minio客户端)

    @Data
    @Component
    public class MinIoClientConfig {
    
        @Value("${minio.endpoint}")
        private String endpoint;
    
        @Value("${minio.accessKey}")
        private String accessKey;
    
        @Value("${minio.secretKey}")
        private String secreKey;
    
        /**
         * 注入minio客户端
         * @return
         */
        @Bean
        public MinioClient minioClient(){
            return MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey,secreKey)
                    .build();
        }
    }
    
  8. 工具类

    /**
     * 功能描述:MinioUtils
     *
     * @author: sc
     * @Date: 2022/12/27
     * @Time: 10:26
     */
    @Component
    public class MinioUtils {
        @Autowired
        private MinioClient minioClient;
    
        @Value("${minio.bucketName}")
        private String bucketName;
    
        /**
         * description: 判断bucket是否存在,不存在则创建
         *
         * @return: void
         */
        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();
            }
        }
    
        /**
         * 创建存储bucket
         * @param bucketName 存储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
         * @param bucketName 存储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;
        }
    
        /**
         * description: 上传文件
         *
         * @param multipartFile
         * @return: java.lang.String
         */
        public List<String> upload(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();
                        }
                    }
                }
                names.add(fileName);
            }
            return names;
        }
    
        /**
         * description: 下载文件
         *
         * @param fileName
         * @return: org.springframework.http.ResponseEntity<byte [ ]>
         */
        public ResponseEntity<byte[]> download(String fileName) {
            ResponseEntity<byte[]> responseEntity = 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);
                //封装返回值
                byte[] bytes = out.toByteArray();
                HttpHeaders headers = new HttpHeaders();
                try {
                    headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                headers.setContentLength(bytes.length);
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
                headers.setAccessControlExposeHeaders(Arrays.asList("*"));
                responseEntity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
            } 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 responseEntity;
        }
    
        /**
         * 查看文件对象
         * @param bucketName 存储bucket名称
         * @return 存储bucket内文件对象信息
         */
        public List<ObjectItem> listObjects(String bucketName) {
            Iterable<Result<Item>> results = minioClient.listObjects(
                    ListObjectsArgs.builder().bucket(bucketName).build());
            List<ObjectItem> objectItems = new ArrayList<>();
            try {
                for (Result<Item> result : results) {
                    Item item = result.get();
                    ObjectItem objectItem = new ObjectItem();
                    objectItem.setObjectName(item.objectName());
                    objectItem.setSize(item.size());
                    objectItems.add(objectItem);
                }
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
            return objectItems;
        }
    
        /**
         * 批量删除文件对象
         * @param bucketName 存储bucket名称
         * @param objects 对象名称集合
         */
        public Iterable<Result<DeleteError>> removeObjects(String bucketName, 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;
        }
    
    }
    

    实体类

    /**
     * 功能描述:
     *
     * @author: sc
     * @Date: 2022/12/27
     * @Time: 10:25
     */
    @Data
    public class ObjectItem {
        private String objectName;
        private Long size;
    }
    
    
  9. 编写Controller

    /**
     * 功能描述:
     *
     * @author: sc
     * @Date: 2022/12/27
     * @Time: 10:35
     */
    @RestController
    public class MinioController {
        @Resource
        private MinioUtils minioUtils;
        @Value("${minio.endpoint}")
        private String address;
        @Value("${minio.bucketName}")
        private String bucketName;
    
        /**
         * 文件上传
         * @param files
         * @return
         */
        @PostMapping("/upload")
        public Object upload(MultipartFile[] files){
            List<String> uploadUrl = new ArrayList<>();
            List<String> upload = minioUtils.upload(files);
            for (String s : upload) {
                uploadUrl.add(address+"/"+bucketName+"/"+s);
            }
            return uploadUrl;
        }
    
        /**
         * 移除图片
         * @param imgUrlList
         * @return
         */
        @PostMapping("/remove")
        public Object remove(@RequestBody List<String> imgUrlList){
            Iterable<Result<DeleteError>> img = minioUtils.removeObjects("img", imgUrlList);
            return img;
        }
    
        /**
         * 下载图片
         * @param fileName
         * @return
         */
        @GetMapping("/download/{fileName}")
        public Object download(@PathVariable("fileName") String fileName){
            ResponseEntity<byte[]> download = minioUtils.download(fileName);
            return download;
        }
    }
    

Linux安装教程

posted @ 2022-12-27 15:00  striver-sc  阅读(296)  评论(0编辑  收藏  举报