• Spring Boot 集成 MinIO 实现文件上传、下载和删除


    MinIO 是一种开源的对象存储服务,它基于云原生架构构建,并提供了高性能、易于扩展和安全的存储解决方案。

    一.安装和配置 MinIO 服务器

    为了演示方便,本文采用Windows安装 

    1.在官方网站下载MinIO 安装文件,地址:https://dl.minio.org.cn/server/minio/release/windows-amd64/minio.exe; 

    2.在minio.exe目录下创建start.bat配置启动文件:"D:\Java\MinIo"是服务启动时文件存放的位置 

    minio.exe server D:\Java\MinIo

    3.双击minio.exe文件启动

     

    4.创建一个 Spring Boot 项目

            1.创建一个 Spring Boot 项目

            2.添加依赖,注意依赖版本

    1. <dependency>
    2. <groupId>commons-iogroupId>
    3. <artifactId>commons-ioartifactId>
    4. <version>2.4version>
    5. dependency>
    6. <dependency>
    7. <groupId>commons-fileuploadgroupId>
    8. <artifactId>commons-fileuploadartifactId>
    9. <version>1.4version>
    10. dependency>
    11. <dependency>
    12. <groupId>io.miniogroupId>
    13. <artifactId>minioartifactId>
    14. <version>8.4.3version>
    15. dependency>
    16. <dependency>
    17. <groupId>com.squareup.okhttp3groupId>
    18. <artifactId>okhttpartifactId>
    19. <version>4.8.1version>
    20. dependency>

    二.配置文件

            1.yaml配置文件

    1. #MinIO配置
    2. minio:
    3. endpoint: http://127.0.0.01:9000 #连接地址
    4. accessKey: minioadmin#账号 默认minioadmin
    5. secretKey: minioadmin#密码 默认minioadmin
    6. bucketName: contractfile #桶名 存放合同文件 桶名校验规则:!name.matches("^[a-z0-9][a-z0-9\\.\\-]+[a-z0-9]$")

             2.配置类,用来连接Minio

    1. @Data
    2. @Configuration
    3. @ConfigurationProperties(prefix = "minio")
    4. public class MinioConfig {
    5. //连接地址
    6. private String endpoint;
    7. //账号 默认minioadmin
    8. private String accessKey;
    9. //密码 默认minioadmin
    10. private String secretKey;
    11. @Bean
    12. public MinioClient minioClient() {
    13. MinioClient minioClient = MinioClient.builder()
    14. .endpoint(endpoint)
    15. .credentials(accessKey, secretKey)
    16. .build();
    17. return minioClient;
    18. }
    19. }

            3.工具类,用来操作文件

    1. @Slf4j
    2. @Component
    3. public class MinioUtils {
    4. @Autowired
    5. private MinioClient minioClient;
    6. @Value("${minio.bucketName}")
    7. private String bucketName;
    8. /**
    9. * 操作文件时先创建Bucket
    10. * 如果没有Bucket则创建
    11. *
    12. * @param bucketName
    13. */
    14. @SneakyThrows(Exception.class)
    15. public void createBucket(String bucketName) {
    16. if (!bucketExists(bucketName)) {
    17. minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
    18. }
    19. }
    20. /**
    21. * 判断Bucket是否存在,true:存在,false:不存在
    22. *
    23. * @param bucketName
    24. * @return
    25. */
    26. @SneakyThrows(Exception.class)
    27. public boolean bucketExists(String bucketName) {
    28. return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
    29. }
    30. /**
    31. * 判断文件是否存在
    32. *
    33. * @param bucketName
    34. * @param fileRealName
    35. * @return
    36. */
    37. public boolean isObjectExist(String bucketName, String fileRealName) {
    38. boolean exist = true;
    39. try {
    40. minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(fileRealName).build());
    41. } catch (Exception e) {
    42. log.error("[Minio工具类]>>>> 判断文件是否存在, 异常:", e);
    43. exist = false;
    44. }
    45. return exist;
    46. }
    47. /**
    48. * 使用MultipartFile进行文件上传
    49. *
    50. * @param bucketName 存储桶
    51. * @param file 文件
    52. * @param fileRealName 文件名
    53. * @return 文件下载外链
    54. */
    55. @SneakyThrows(Exception.class)
    56. public String uploadFile(String bucketName, MultipartFile file, String fileRealName) {
    57. createBucket(bucketName);
    58. InputStream inputStream = file.getInputStream();
    59. minioClient.putObject(
    60. PutObjectArgs.builder()
    61. .bucket(bucketName)
    62. .object(fileRealName)
    63. .contentType(file.getContentType())
    64. .stream(inputStream, inputStream.available(), -1)
    65. .build());
    66. GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder()
    67. .bucket(bucketName)
    68. .object(fileRealName)
    69. .method(Method.GET).build();
    70. return minioClient.getPresignedObjectUrl(args);
    71. }
    72. /**
    73. * 删除文件
    74. *
    75. * @param bucketName 存储桶
    76. * @param fileRealName 文件名称
    77. */
    78. @SneakyThrows(Exception.class)
    79. public void removeFile(String bucketName, String fileRealName) {
    80. createBucket(bucketName);
    81. minioClient.removeObject(
    82. RemoveObjectArgs.builder()
    83. .bucket(bucketName)
    84. .object(fileRealName)
    85. .build());
    86. }
    87. /**
    88. * 下载文件
    89. *
    90. * @param httpServletResponse httpServletResponse
    91. * @param fileRealName 文件存储名称
    92. * @param fileName 文件下载名称
    93. * @throws IOException IOException
    94. */
    95. public void downloadFile(String bucketName, String fileRealName, String fileName, HttpServletResponse httpServletResponse) throws Exception {
    96. createBucket(bucketName);
    97. //获取文件流
    98. InputStream inputStream = minioClient.getObject(GetObjectArgs.builder()
    99. .bucket(bucketName)
    100. .object(fileRealName)
    101. .build());
    102. //设置响应头信息,告诉前端浏览器下载文件
    103. httpServletResponse.setContentType("application/octet-stream;charset=UTF-8");
    104. httpServletResponse.setCharacterEncoding("UTF-8");
    105. httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
    106. //获取输出流进行写入数据
    107. OutputStream outputStream = httpServletResponse.getOutputStream();
    108. // 将输入流复制到输出流
    109. byte[] buffer = new byte[4096];
    110. int bytesRead = -1;
    111. while ((bytesRead = inputStream.read(buffer)) != -1) {
    112. outputStream.write(buffer, 0, bytesRead);
    113. }
    114. // 关闭流资源
    115. inputStream.close();
    116. outputStream.close();
    117. }
    118. }

  • 相关阅读:
    UML建模
    物联网,智慧城市的数字化转型引擎
    基于J2EE的网上体育用品销售系统设计与实现(SSH)
    【Git】已经在拉取时以HTTP的URL拉取的仓库使用SSH的URL进行push
    LeetCode 1280. 学生们参加各科测试的次数
    【小程序】首屏渲染优化
    解释索引是什么以及它们是如何提高查询性能的
    新外卖霸王餐小程序、H5、微信公众号版外卖系统源码
    Hexagon_V65_Programmers_Reference_Manual(26)
    python 小案例87
  • 原文地址:https://blog.csdn.net/weixin_58724261/article/details/133313868