• springboot 集成minio 实现文件上传


    引入依赖
    <dependency>
      <groupId>io.miniogroupId>
      <artifactId>minioartifactId>
      <version>8.2.0version>
    dependency>
    
    

    因为我是后端开发需要使用knife4j

    
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0modelVersion>
      <groupId>com.orchidsgroupId>
      <artifactId>springmybatisplusartifactId>
      <version>0.0.1-SNAPSHOTversion>
      <name>springmybatisplusname>
      <description>springmybatisplusdescription>
      <properties>
        <java.version>17java.version>
        <project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding>
        <spring-boot.version>3.0.2spring-boot.version>
        <knife4j.version>4.1.0knife4j.version>
        <mybatis-plus.version>3.5.6mybatis-plus.version>
        <minio.version>8.2.0minio.version>
      properties>
      <dependencies>
        <dependency>
          <groupId>org.springframework.bootgroupId>
          <artifactId>spring-boot-starter-webartifactId>
        dependency>
    
        <dependency>
          <groupId>com.mysqlgroupId>
          <artifactId>mysql-connector-jartifactId>
          <scope>runtimescope>
        dependency>
        <dependency>
          <groupId>org.projectlombokgroupId>
          <artifactId>lombokartifactId>
          <optional>trueoptional>
        dependency>
        <dependency>
          <groupId>org.springframework.bootgroupId>
          <artifactId>spring-boot-starter-testartifactId>
          <scope>testscope>
        dependency>
        <dependency>
          <groupId>com.github.xiaoymingroupId>
          <artifactId>knife4j-openapi3-jakarta-spring-boot-starterartifactId>
          <version>${knife4j.version}version>
        dependency>
        <dependency>
          <groupId>com.baomidougroupId>
          <artifactId>mybatis-plus-boot-starterartifactId>
          <version>${mybatis-plus.version}version>
        dependency>
        <dependency>
          <groupId>io.miniogroupId>
          <artifactId>minioartifactId>
          <version>${minio.version}version>
        dependency>
      dependencies>
      <dependencyManagement>
        <dependencies>
          <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-dependenciesartifactId>
            <version>${spring-boot.version}version>
            <type>pomtype>
            <scope>importscope>
          dependency>
        dependencies>
      dependencyManagement>
      
      <build>
        <plugins>
          <plugin>
            <groupId>org.apache.maven.pluginsgroupId>
            <artifactId>maven-compiler-pluginartifactId>
            <version>3.11.0version>
            <configuration>
              <compilerArgs>
                <arg>-parametersarg>
              compilerArgs>
                <source>15source>
                <target>15target>
              configuration>
              plugin>
              plugins>
              build>
    
    
              project>
    
    
    编写配置信息
    minio:
      endpoint: http://localhost:9000
      access-key: minioadmin
      secret-key: minioadmin
      bucket-name: lovehouse
    
    获取配置信息
    • 编写实体类
    package com.orchids.springmybatisplus.common.minio;
    
    import lombok.Data;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.context.properties.EnableConfigurationProperties;
    
    /**
     * @Author qwh
     * @Date 2024/6/1 9:54
     */
    @Data
    @ConfigurationProperties(prefix = "minio")
    public class MinioProperties {
    
        private String endpoint;
    
        private String accessKey;
    
        private String secretKey;
    
        private String bucketName;
    }
    
    
    编写配置文件 交给spring 管理 获取实体类信息
    package com.orchids.springmybatisplus.common.minio;
    
    import io.minio.MinioClient;
    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;
    
    /**
     * @Author qwh
     * @Date 2024/6/1 9:48
     */
    @Configuration
    @EnableConfigurationProperties(MinioProperties.class)
    public class MinioConfiguration {
        @Autowired
        private MinioProperties minioProperties;
        @Bean
        public MinioClient minioClient(){
            return MinioClient.builder().endpoint(minioProperties.getEndpoint()).credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey()).build();
        }
    }
    
    
    controller
    package com.orchids.springmybatisplus.web.controller;
    
    import com.orchids.springmybatisplus.model.result.Result;
    import com.orchids.springmybatisplus.web.service.FileService;
    import io.minio.errors.*;
    import io.swagger.v3.oas.annotations.Operation;
    import io.swagger.v3.oas.annotations.tags.Tag;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.MultipartFile;
    
    
    
    /**
     * @Author qwh
     * @Date 2024/6/1 10:07
     */
    @Tag(name = "文件上传")
    @RestController
    @RequestMapping("/file")
    public class FileUpLoadController {
        @Autowired
        private FileService fileService;
    
        @Operation(summary = "文件上传")
        @PostMapping("upload")
        public Result<String> upload(@RequestParam MultipartFile file) {
            //接口改造
            try {
                String url = fileService.upload(file);
                return Result.ok(url);
            } catch (Exception e) {
                return Result.fail();
            }
        }
    }
    
    
    service
    package com.orchids.springmybatisplus.web.service;
    
    import io.minio.errors.*;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.IOException;
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    
    /**
     * @Author qwh
     * @Date 2024/6/1 10:17
     */
    public interface FileService {
        String upload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException;
    }
    
    

    实现类

    package com.orchids.springmybatisplus.web.service.impl;
    
    import com.orchids.springmybatisplus.common.minio.MinioConfiguration;
    import com.orchids.springmybatisplus.common.minio.MinioProperties;
    import com.orchids.springmybatisplus.web.service.FileService;
    import io.minio.*;
    import io.minio.errors.*;
    import okhttp3.internal.io.FileSystem;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.IOException;
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.UUID;
    
    /**
     * @Author qwh
     * @Date 2024/6/1 10:18
     */
    @Service
    public class FileServiceImpl implements FileService {
        @Autowired
        private MinioClient minioClient;
        @Autowired
        private MinioProperties minioProperties;
    
        @Override
        public String upload(MultipartFile file) throws ServerException, InsufficientDataException, ErrorResponseException, IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
            boolean bucketed = minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (!bucketed) {
                // 创建桶
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
                //设置文件唯一名称
                // 设置桶的读写权限
                minioClient.setBucketPolicy(SetBucketPolicyArgs.builder()
                        .bucket(minioProperties.getBucketName())
                        .config(createBucketPolicyConfig(minioProperties.getBucketName()))
                        .build());
            }
            // 上传文件
            String filename = new SimpleDateFormat("yyyyMMdd").format(new Date()) + "/" + UUID.randomUUID() + "-" + file.getOriginalFilename();
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(minioProperties.getBucketName())
                    .object(filename)
                    .stream(file.getInputStream(), file.getSize(), -1)
                    .contentType(file.getContentType())
                    .build());
            return String.join("/", minioProperties.getEndpoint(), minioProperties.getBucketName(), filename);
        }
    
        private String createBucketPolicyConfig(String bucketName) {
    
            return """
                    {
                      "Statement" : [ {
                        "Action" : "s3:GetObject",
                        "Effect" : "Allow",
                        "Principal" : "*",
                        "Resource" : "arn:aws:s3:::%s/*"
                      } ],
                      "Version" : "2012-10-17"
                    }
                    """.formatted(bucketName);
        }
    }
    
    
  • 相关阅读:
    我的创作纪念日
    消息队列 - RabbitMQ
    C++基础知识(十四)--- vector容器
    (Java)Mybatis学习笔记(四)
    Python 数据分析入门教程:Numpy、Pandas、Matplotlib和Scikit-Learn详解
    运营商IMS网间互联互通组网关键技术研究
    Go整合Logrus实现日志打印
    spring面试题
    种草模式崛起!小红书KOL达人种草成推广热门方向!
    NodeRed系列——websoket展示数据
  • 原文地址:https://blog.csdn.net/qq_62383709/article/details/139372111