首页 > 编程语言 >Java中如何实现minio文件上传

Java中如何实现minio文件上传

时间:2024-09-06 12:52:35浏览次数:6  
标签:Java String param inputStream org import 上传 minio

一、导入minio依赖

这里还要导入lombok是因为在MinIOConfig类中使用了@Data注解,正常来说导入minio依赖就够了


<dependency>  

   <groupId>io.minio</groupId>  

   <artifactId>minio</artifactId>  

   <version>7.1.0</version>  

</dependency>


<dependency>  

   <groupId>org.projectlombok</groupId>  

   <artifactId>lombok</artifactId>  

   <version>1.18.20</version>  

   <scope>provided</scope>  

</dependency>



二、添加配置

application.yml

这些配置都是在创建minio的docker容器的时候就已经定好的,按照自己的配置去改一改就可以了。需要自定义的就一个桶名称bucket



minio:  

 # MinIO服务器地址  

 endpoint: http://192.168.200.128:9000  

 # MinIO服务器访问凭据  

 accessKey: minio  

 secretKey: minio123  

 # MinIO桶名称  

 bucket: test  

 # MinIO读取路径前缀  

 readPath: http://192.168.200.128:9000



MinIOConfig

通过读取配置创建minioClient对象


package com.ruoyi.minio.config;  

 

 

import com.ruoyi.minio.service.FileStorageService;  

import io.minio.MinioClient;  

import lombok.Data;  

import org.springframework.beans.factory.annotation.Autowired;  

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;  

import org.springframework.boot.context.properties.EnableConfigurationProperties;  

import org.springframework.context.annotation.Bean;  

import org.springframework.context.annotation.Configuration;  

 

 

@Data  

@Configuration  

@EnableConfigurationProperties({MinIOConfigProperties.class})  

//当引入FileStorageService接口时  

@ConditionalOnClass(FileStorageService.class)  

public class MinIOConfig {  

 

   @Autowired  

   private MinIOConfigProperties minIOConfigProperties;  

 

   @Bean  

   public MinioClient buildMinioClient() {  

       return MinioClient  

               .builder()  

               .credentials(minIOConfigProperties.getAccessKey(), minIOConfigProperties.getSecretKey())  

               .endpoint(minIOConfigProperties.getEndpoint())  

               .build();  

   }  

}



MinIOConfigProperties

package com.ruoyi.minio.config;  

 

 

import lombok.Data;  

import org.springframework.boot.context.properties.ConfigurationProperties;  

 

import java.io.Serializable;  

 

@Data  

@ConfigurationProperties(prefix = "minio")  // 文件上传 配置前缀file.oss  

public class MinIOConfigProperties implements Serializable {  

 

   private String accessKey;  

   private String secretKey;  

   private String bucket;  

   private String endpoint;  

   private String readPath;  

}



三、导入工具类

Service

package com.ruoyi.minio.service;  

 

import java.io.InputStream;  

 

public interface FileStorageService {  

 

 

   /**  

    *  上传图片文件  

    * @param prefix  文件前缀  

    * @param filename  文件名  

    * @param inputStream 文件流  

    * @return  文件全路径  

    */  

   public String uploadImgFile(String prefix, String filename,InputStream inputStream);  

 

   /**  

    *  上传html文件  

    * @param prefix  文件前缀  

    * @param filename   文件名  

    * @param inputStream  文件流  

    * @return  文件全路径  

    */  

   public String uploadHtmlFile(String prefix, String filename,InputStream inputStream);  

 

   /**  

    * 删除文件  

    * @param pathUrl  文件全路径  

    */  

   public void delete(String pathUrl);  

 

   /**  

    * 下载文件  

    * @param pathUrl  文件全路径  

    * @return  

    *  

    */    public byte[]  downLoadFile(String pathUrl);  

 

}



ServiceImpl

package com.heima.file.service.impl;



import com.heima.file.config.MinIOConfig;

import com.heima.file.config.MinIOConfigProperties;

import com.heima.file.service.FileStorageService;

import io.minio.GetObjectArgs;

import io.minio.MinioClient;

import io.minio.PutObjectArgs;

import io.minio.RemoveObjectArgs;

import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.boot.context.properties.EnableConfigurationProperties;

import org.springframework.context.annotation.Import;

import org.springframework.util.StringUtils;


import java.io.ByteArrayOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.text.SimpleDateFormat;

import java.util.Date;


@Slf4j

@EnableConfigurationProperties(MinIOConfigProperties.class)

@Import(MinIOConfig.class)

public class MinIOFileStorageService implements FileStorageService {


   @Autowired

   private MinioClient minioClient;


   @Autowired

   private MinIOConfigProperties minIOConfigProperties;


   private final static String separator = "/";


   /**

    * @param dirPath

    * @param filename  yyyy/mm/dd/file.jpg

    * @return

    */

   public String builderFilePath(String dirPath,String filename) {

       StringBuilder stringBuilder = new StringBuilder(50);

       if(!StringUtils.isEmpty(dirPath)){

           stringBuilder.append(dirPath).append(separator);

       }

       SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

       String todayStr = sdf.format(new Date());

       stringBuilder.append(todayStr).append(separator);

       stringBuilder.append(filename);

       return stringBuilder.toString();

   }


   /**

    *  上传图片文件

    * @param prefix  文件前缀

    * @param filename  文件名

    * @param inputStream 文件流

    * @return  文件全路径

    */

   @Override

   public String uploadImgFile(String prefix, String filename,InputStream inputStream) {

       String filePath = builderFilePath(prefix, filename);

       try {

           PutObjectArgs putObjectArgs = PutObjectArgs.builder()

                   .object(filePath)

                   .contentType("image/jpg")

                   .bucket(minIOConfigProperties.getBucket()).stream(inputStream,inputStream.available(),-1)

                   .build();

           minioClient.putObject(putObjectArgs);

           StringBuilder urlPath = new StringBuilder(minIOConfigProperties.getReadPath());

           urlPath.append(separator+minIOConfigProperties.getBucket());

           urlPath.append(separator);

           urlPath.append(filePath);

           return urlPath.toString();

       }catch (Exception ex){

           log.error("minio put file error.",ex);

           throw new RuntimeException("上传文件失败");

       }

   }


   /**

    *  上传html文件

    * @param prefix  文件前缀

    * @param filename   文件名

    * @param inputStream  文件流

    * @return  文件全路径

    */

   @Override

   public String uploadHtmlFile(String prefix, String filename,InputStream inputStream) {

       String filePath = builderFilePath(prefix, filename);

       try {

           PutObjectArgs putObjectArgs = PutObjectArgs.builder()

                   .object(filePath)

                   .contentType("text/html")

                   .bucket(minIOConfigProperties.getBucket()).stream(inputStream,inputStream.available(),-1)

                   .build();

           minioClient.putObject(putObjectArgs);

           StringBuilder urlPath = new StringBuilder(minIOConfigProperties.getReadPath());

           urlPath.append(separator+minIOConfigProperties.getBucket());

           urlPath.append(separator);

           urlPath.append(filePath);

           return urlPath.toString();

       }catch (Exception ex){

           log.error("minio put file error.",ex);

           ex.printStackTrace();

           throw new RuntimeException("上传文件失败");

       }

   }


   /**

    * 删除文件

    * @param pathUrl  文件全路径

    */

   @Override

   public void delete(String pathUrl) {

       String key = pathUrl.replace(minIOConfigProperties.getEndpoint()+"/","");

       int index = key.indexOf(separator);

       String bucket = key.substring(0,index);

       String filePath = key.substring(index+1);

       // 删除Objects

       RemoveObjectArgs removeObjectArgs = RemoveObjectArgs.builder().bucket(bucket).object(filePath).build();

       try {

           minioClient.removeObject(removeObjectArgs);

       } catch (Exception e) {

           log.error("minio remove file error.  pathUrl:{}",pathUrl);

           e.printStackTrace();

       }

   }



   /**

    * 下载文件

    * @param pathUrl  文件全路径

    * @return  文件流

    *

    */

   @Override

   public byte[] downLoadFile(String pathUrl)  {

       String key = pathUrl.replace(minIOConfigProperties.getEndpoint()+"/","");

       int index = key.indexOf(separator);

       String bucket = key.substring(0,index);

       String filePath = key.substring(index+1);

       InputStream inputStream = null;

       try {

           inputStream = minioClient.getObject(GetObjectArgs.builder().bucket(minIOConfigProperties.getBucket()).object(filePath).build());

       } catch (Exception e) {

           log.error("minio down file error.  pathUrl:{}",pathUrl);

           e.printStackTrace();

       }


       ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

       byte[] buff = new byte[100];

       int rc = 0;

       while (true) {

           try {

               if (!((rc = inputStream.read(buff, 0, 100)) > 0)) break;

           } catch (IOException e) {

               e.printStackTrace();

           }

           byteArrayOutputStream.write(buff, 0, rc);

       }

       return byteArrayOutputStream.toByteArray();

   }

}




四、使用工具类上传文件并返回url



package com.ruoyi.web.controller.utils;  

 

import com.ruoyi.common.core.domain.AjaxResult;  

import com.ruoyi.minio.service.impl.MinIOFileStorageService;  

import org.springframework.beans.factory.annotation.Autowired;  

import org.springframework.web.bind.annotation.GetMapping;  

import org.springframework.web.bind.annotation.PostMapping;  

import org.springframework.web.bind.annotation.RequestMapping;  

import org.springframework.web.bind.annotation.RestController;  

import org.springframework.web.multipart.MultipartFile;  

 

import java.io.FileOutputStream;  

import java.io.IOException;  

import java.io.InputStream;  

@RestController  

@RequestMapping("/minio")  

public class MinioController {  

   @Autowired  

   MinIOFileStorageService minIOFileStorageService;  

 

   @PostMapping("/fileupload")  

   public AjaxResult minIo(MultipartFile multipartFile){  

 

       // 检查multipartFile是否为空  

       if (multipartFile == null || multipartFile.isEmpty()) {  

           return AjaxResult.error("文件为空,无法处理。");  

       }  

       try(InputStream inputStream = multipartFile.getInputStream()) {  // 将MultipartFile转换为InputStream  

           // 上传到MinIO服务器

           // 这里的文件名可以生成随机的名称,防止重复

           String url = minIOFileStorageService.uploadImgFile("testjpg", "test1.jpg", inputStream);  

           return AjaxResult.success(url);  

       } catch (IOException e) {  

           // 处理异常,可能是getInputStream()失败  

           return AjaxResult.error("获取InputStream失败:" + e.getMessage());  

       }  

   }  

 

}




上传成功后在浏览器中访问图片的url就可以看到图片了。


标签:Java,String,param,inputStream,org,import,上传,minio
From: https://blog.51cto.com/u_16271212/11937332

相关文章

  • 从内存层面分析Java 参数传递机制
    在Java中,理解参数传递机制对于编写高效和可维护的代码至关重要。本文将探讨基本数据类型和引用数据类型的参数传递方式,并介绍System.identityHashCode方法及其作用。我们将结合栈帧的概念,通过示例代码来详细解释这些机制。System.identityHashCode的作用System.ident......
  • SSH框架整合实现Java三层架构实例(一)
    HTML前台发送请求代码:1<tr>2<td>选择收派时间</td>3<td>4<inputtype="text"name="takeTimeId"class="easyui-combobox"required="true"5data-options="url:'../........
  • Java静态代码块、构造代码块执行顺序问题
    packagecom.zxl.staticdemo;publicclassBlockTest{static{System.out.println("BlockTest静态代码块执行");}{System.out.println("BlockTest构造代码块执行");}publicBlockTest(){System.out.......
  • [Java基础]hashcode/equals
    hashcode()/equals()/====当==左右两边是基本类型的时候,比较的是数值是否相等;当==左右两边是对象(引用)类型的时候,比较的是p和p2这两个对象所指向的堆中的对象地址对于==来说,不管是比较基本数据类型,还是引用数据类型的变量,其本质比较的都是值,只是引用类型变量存的值是......
  • Java中实现对象和Map之间的转换
    在Java开发中,经常需要将Java对象转换成Map,或者反过来将Map转换成Java对象。这种转换在很多场景下都非常有用,比如在序列化和反序列化过程中、在数据传输和持久化时、或者在进行对象属性的批量操作时。本文将介绍几种不同的方法来实现Java对象和Map之间的相互转换,选择哪种方法取......
  • 基于JAVA 小程序 旅游推荐管理系统,旅行系统
    目录一.研究目的二.系统分析三.系统流程和逻辑四.数据库设计五.页面展示六.源码获取一.研究目的随着互联网技术的快速发展,网络时代的到来,网络信息也将会改变当今社会。各行各业在日常企业经营管理等方面也在慢慢的向规范化和网络化趋势汇合。旅游社交小程序的信息化......
  • JavaScript 中 structuredClone 和 JSON.parse(JSON.stringify()) 克隆对象的区别
    JavaScript中structuredClone和JSON.parse(JSON.stringify())克隆对象的异同点一、什么是structuredClone?1.structuredClone的发展structuredClone是在ECMAScript2021(ES12)标准中引入的,ECMAScript2021规范正式发布于2021年6月自2022年3月起,该功能适用于最......
  • 【Java】【SpringBoot】yml配置文件解析
    yml的常见配置可以详见官方文档。https://docs.spring.io/spring-boot/appendix/application-properties/index.html#appendix.application-properties.server服务器配置server:port:8080#端口servlet:context-path:/#应用程序上下文路径【设置访问路径前缀......
  • java面试题(Spring、Spring MVC)
    点赞关注+收藏,万分感谢!!Spring1、为什么要使用spring?spring提供ioc技术,容器会帮你管理依赖的对象,从而不需要自己创建和管理依赖对象了,更轻松的实现了程序的解耦。spring提供了事务支持,使得事务操作变的更加方便。spring提供了面向切片编程,这样可以更方便的处理某一类......
  • Java高级编程—多线程(完整详解线程的三种实现方式、以及守护线程、出让线程、插入线程
    二十八.多线程文章目录二十八.多线程28.1线程的三种实现方式28.1.1第一种28.1.2第二种28.1.3第三种28.2常见的成员方法28.3守护线程28.4出让线程28.5插入线程28.6线程生命周期28.7同步代码块28.8同步方法28.1线程的三种实现方式继承Thread类的方式进行......