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

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.xdnf.cn/news/17221.html

相关文章:

  • OpenAI 开源模型 GPT-OSS MCP服务器深度解密:从工具集成到系统提示全自动化,浏览器+Python无缝协同的底层逻辑
  • 轻松实现浏览器自动化——AI浏览器自动化框架Stagehand
  • 【R语言】重新绘制高清MaxEnt的单因素响应曲线图像
  • 写Rust GPU内核驱动:GPU驱动工作原理简述
  • 告别Cursor!最强AI编程辅助Claude Code安装到使用全流程讲解
  • Beelzebub靶机
  • 第二十七天(数据结构:图)
  • Linux线程学习
  • Flutter 局部刷新方案对比:ValueListenableBuilder vs. GetBuilder vs. Obx
  • 力扣经典算法篇-46-阶乘后的零(正向步长遍历,逆向步长遍历)
  • 了解大型语言模型:力量与潜力
  • 什么是键值缓存?让 LLM 闪电般快速
  • 每日五个pyecharts可视化图表-bars(6)
  • 关于Android studio调试功能使用
  • 2025年主流开源音视频播放项目深度解析
  • MCU中的USB
  • 聚众识别场景误报率↓76%:陌讯动态密度估计算法实战解析
  • 【C语言】深入理解编译与链接过程
  • 前后端加密传数据实现方案
  • OpenCV入门:图像处理基础教程
  • [优选算法专题一双指针——两数之和](双指针和哈希表)
  • Qwen-Image开源模型实战
  • Spring、Spring MVC、MyBatis 和 Spring Boot的关系
  • 防火墙环境下的全网服务器数据自动化备份平台搭建:基于 rsync 的完整实施指南
  • 板块三章节3——NFS 服务器
  • 秋招笔记-8.7
  • Redis面试精讲 Day 13:Redis Cluster集群设计与原理
  • 解决 Nginx 反代中 proxy_ssl_name 环境变量失效问题:网页能打开但登录失败
  • Vue3获取当前页面相对路径
  • SMT工具实践:Moses工具的配置和小语种平行语料训练统计翻译模型完整实现