当前位置: 首页 > news >正文

springBoot集成minio并实现文件的上传下载

引入依赖

  1. 引入依赖
    在你的Spring Boot项目中,你需要在pom.xml中添加MinIO的依赖。如果你使用的是Maven,可以添加如下依赖:
<dependency><groupId>io.minio</groupId><artifactId>minio</artifactId><version>8.4.0</version> <!-- 确保使用最新版本 -->
</dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency>
  1. 配置MinIO属性
    在application.properties或application.yml中,添加MinIO的配置参数:

minio.url=http://localhost:9000 # MinIO服务的URL
minio.access-key=YOUR_ACCESS_KEY # 替换为你的Access Key
minio.secret-key=YOUR_SECRET_KEY # 替换为你的Secret Key
minio.bucket-name=YOUR_BUCKET_NAME # 替换为你的桶名

或者ymal 格式
minio:
url: http://192.168.5.10:9000
access-key: minioUser
secret-key: minioUser001
bucket-name: m-test

编写配置类

3. 创建MinIO配置类
你可以创建一个配置类,用于初始化MinIO客户端:
import io.minio.MinioClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MinioConfig {@Value("${minio.url}")private String minioUrl;@Value("${minio.access-key}")private String accessKey;@Value("${minio.secret-key}")private String secretKey;@Beanpublic MinioClient minioClient() {return MinioClient.builder().endpoint(minioUrl).credentials(accessKey, secretKey).build();}
}
  1. 创建服务类
    接下来,你可以创建一个服务类来处理文件的上传和下载等操作:
import com.wl.std.kaixin.MinioConfig;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.GetObjectArgs;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;@Service
public class MinioService {@Autowiredprivate MinioClient minioClient;@Value("${minio.bucket-name}")private String bucketName;@AutowiredMinioConfig minioConfig;public InputStream downloadFile(String objectName) throws Exception {return minioClient.getObject(GetObjectArgs.builder().bucket(bucketName).object(objectName).build());}public Object uploadFile(String fileName, MultipartFile file)  {try {if(file == null || file.getSize() == 0){System.out.print("文件内容为空");throw new RuntimeException("文件内容不允许为空");}InputStream inputStream = file.getInputStream();PutObjectArgs putObjectArgs = PutObjectArgs.builder().bucket(bucketName).object(fileName).contentType(file.getContentType()).stream(inputStream, file.getSize(), -1).build();minioClient.putObject(putObjectArgs);inputStream.close();return "%s/%s/%s".formatted(minioConfig.getMinioUrl(), bucketName, fileName);} catch (Exception e) {e.printStackTrace();}return "";}
}

创建请求类


import com.wl.std.kaixin.service.MinioService;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;import javax.print.attribute.standard.Media;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;@RestController
@RequestMapping("/files")
public class FileController {@Autowiredprivate MinioService minioService;//文件上传@PostMapping(value = "/upload",consumes = MediaType.MULTIPART_FORM_DATA_VALUE)public Object uploadFile(@RequestParam("file") MultipartFile file){String fileName = file.getOriginalFilename();Map<String,Object> result = new HashMap<>();try {var fileUrl = minioService.uploadFile(fileName,file);result.put("success",true);result.put("data",fileUrl);System.out.print("upload success and result is: "+result);}catch (Exception e){result.put("success",false);result.put("data","");}return result;}@GetMapping("/download")public void download(@RequestParam("fileName") String fileName, HttpServletResponse response){try {InputStream inputStream = minioService.downloadFile(fileName);ServletOutputStream outputStream = response.getOutputStream();response.setHeader("Content-Disposition","attachment ; filename="+ URLEncoder.encode(fileName, StandardCharsets.UTF_8));response.setCharacterEncoding("utf-8");response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);byte[] bytes = new byte[1024];int length;while ((length = inputStream.read(bytes)) > 0){outputStream.write(bytes,0,length);}outputStream.close();inputStream.close();}catch (Exception e){System.out.print("error:"+e.getMessage());}}}使用postman验证上传下载```
上传:
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/4f4782314d464a47a68d6880b60d786f.png)
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/76cd26414df440d9adc1c678a548d0d4.png)
下载:
![在这里插入图片描述](https://i-blog.csdnimg.cn/direct/c7ce7cda51294ff7b7ecd90c800a2130.png)
http://www.dtcms.com/a/321223.html

相关文章:

  • 华为网路设备学习-28(BGP协议 三)路由策略
  • 怎么实现对三菱PLC的远程调试和PLC远程维护?
  • 【世纪龙科技】数智重构车身实训-汽车车身测量虚拟实训软件
  • 矩阵中的最长递增路径-记忆化搜索
  • 【ESP32-menuconfig(1) -- Build Type及Bootloader config】
  • Vue 项目安全设置方案:XSS/CSRF 防护指南
  • 浅谈:如何复现修复Bug?
  • OpenCV 3 终极指南:创建炫酷自定义窗口与图像显示的艺术
  • 【代码随想录day 14】 力扣 111.二叉树的最小深度
  • Cesium 无人机视角飞行漫游,截屏
  • RabbitMQ详情介绍—七种工作模式
  • springmvc4+hibernate4整合框架的搭建
  • 库函数版独立按键用位运算方式实现(STC8)
  • Array Description(Dynamic programming)
  • 【网络编程】IO多路转接——epoll
  • Java文件读写(IO、NIO)
  • 第39周——训练自己的数据集
  • 汇编语言和高级语言的差异
  • BGP综合实验练习作业
  • Fabarta个人专属智能体:三维搜索链+动态大纲重构教材开发范式
  • Omron(欧姆龙)SysmacStudio软件下载,定期更新(最新更新到1.63升级包)
  • npm run 常见脚本
  • BGP协议笔记
  • 【新启航】航空飞机起落架深孔型腔的内轮廓测量方法探究 - 激光频率梳 3D 轮廓检测
  • 2025华数杯数学建模A题【 多孔膜光反射性能的优化与控制】原创论文讲解(含完整python代码)
  • 避免“卡脖子”!如何减少内存I/O延迟对程序的影响?
  • 机器学习——支持向量机(SVM)实战案例
  • 操作系统-实验-进程
  • 机器学习之支持向量机(原理)
  • svm的一些应用