SpringBoot3整合Minio实现文件上传

SpringBoot3整合Minio实现文件上传

本文将零开始讲解minio实现文件上传的过程,包括其中可能会出现的一个问题以及解决办法。
首先进入官网:https://www.minio.org.cn/download.shtml#/macos

一、下载

我们需要先下载minio的服务端(客户端不下,因为本文将用SpingBoot做客户端)
在这里插入图片描述
选择自己电脑的型号,因为我用的是mac,所以用mac版本演示,windows也差不多。官网提供了两种下载方法,分别是HomeBrew和Binary,这里推荐下载二进制文件,因为homebrew下载太慢了。
如果不习惯用curl命令下载,这里给出下载地址:https://dl.minio.org.cn/server/minio/release/darwin-amd64/minio
然后按照官网给的命令,使用终端启动服务器

chmod +x minio
MINIO_ROOT_USER=admin MINIO_ROOT_PASSWORD=password ./minio server mnt/data --console-address ":9001"
会有如下界面

在这里插入图片描述
之后打开浏览器:http://localhost:9001会弹出一个登陆界面,按照你刚刚启动时输入的账号密码登陆上去。

二、创建配置项

1、添加bucketName
在这里插入图片描述
2、创建从access-key和secret-key
在这里插入图片描述
注意接下来你需要把SecretKey放在小本本上记好,后面找不到,项目里也需要这个。手快的人就再创建一个哈😁

三、搭建SpringBoot项目

使用idea创建项目后,引用基本的依赖

            <dependency>
                <groupId>io.minio</groupId>
                <artifactId>minio</artifactId>
                <version>8.5.2</version>
            </dependency>
            <!--web相关-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
                <version>3.1.2</version>
            </dependency>


在yml文件中添加刚刚在管理界面创建的内容

spring:
  cloud:
    storage:
      minio:
        bucketName: your-bucketName
        endpoint: http://localhost:9000
        access-key: your-access-key
        secret-key: your-secret-key

创建一个简单的文件存储bean

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 MinioConfiguration {

    @Value("${spring.cloud.storage.minio.endpoint}")
    private String minioEndpoint;

    @Value("${spring.cloud.storage.minio.access-key}")
    private String minioAccessKey;

    @Value("${spring.cloud.storage.minio.secret-key}")
    private String minioSecretKey;
	
	

    @Bean
    public MinioClient minioClient() {
        return MinioClient.builder()
                .endpoint(minioEndpoint)
                .credentials(minioAccessKey, minioSecretKey)
                .build();
    }
}

编写一个上传逻辑

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.stereotype.Service;

@Service
public class FileService {

	@Value("${spring.cloud.storage.minio.bucket-name}")
    private String bucketName;

    private final MinioClient minioClient;

    public MinioService(MinioClient minioClient) {
        this.minioClient = minioClient;
    }


    public String upload(byte[] content, String path, String type) throws Exception{
        // 执行上传
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName) // bucket 必须传递
                .contentType(type)
                .object(path) // 相对路径作为 key
                .stream(new ByteArrayInputStream(content), content.length, -1) // 文件内容
                .build());
        return endpoint+"/"+bucketName+"/"+path;
    }
}

最后再编写一个controller接口就行

@RestController
@RequestMapping("/infra/file")
@Validated
public class FileController {

    @Resource
    private FileService fileService;

    @PostMapping("/upload")
    @Operation(summary = "上传文件")

    public CommonResult<String> uploadFile(FileUploadReqVO uploadReqVO) throws Exception {
        MultipartFile file = uploadReqVO.getFile();
        String path = uploadReqVO.getPath();
        return CommonResult.success(fileService.createFile(file.getOriginalFilename(), path, IoUtil.readBytes(file.getInputStream())));
    }
}

入参类

@Schema(description = "管理后台 - 上传文件 Request VO")
@Data
public class FileUploadReqVO {

    @Schema(description = "文件附件")
    @NotNull(message = "文件附件不能为空")
    private MultipartFile file;

    @Schema(description = "文件附件", example = "yudaoyuanma.png")
    private String path;

}

开始测试
在这里插入图片描述
可以看到,上传成功
在这里插入图片描述

四、可能出现的问题

1、文件超过1M报错
解决办法:在yml添加配置

  # Servlet 配置
spring:
  servlet:
    # 文件上传相关配置项
    multipart:
      max-file-size: 16MB # 单个文件大小
      max-request-size: 32MB # 设置总上传的文件大小

2、出现报错如下:

curl --progress-bar -O https://dl.minio.org.cn/server/minio/release/darwin-amd64/minio
chmod +x minio
MINIO_ROOT_USER=admin MINIO_ROOT_PASSWORD=password ./minio server /mnt/data --console-address ":9001"

解决办法:
配置中的endpoint应该对应的是S3启动的API
在这里插入图片描述
在这里插入图片描述
端口要对应上。

  • 3
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
首先,需要引入minio的依赖: ``` <dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>8.0.2</version> </dependency> ``` 然后,在application.properties中配置minio的连接信息: ``` minio.url=http://localhost:9000 minio.accessKey=minioadmin minio.secretKey=minioadmin minio.bucketName=test ``` 接着,创建一个MinioService类,用于处理文件上传和下载: ``` @Service public class MinioService { @Value("${minio.url}") private String minioUrl; @Value("${minio.accessKey}") private String accessKey; @Value("${minio.secretKey}") private String secretKey; @Value("${minio.bucketName}") private String bucketName; private final MinioClient minioClient = new MinioClient(minioUrl, accessKey, secretKey); public void upload(MultipartFile file) throws Exception { // 生成文件名 String originalFilename = file.getOriginalFilename(); String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf(".")); // 上传文件 minioClient.putObject(PutObjectArgs.builder() .bucket(bucketName) .object(fileName) .stream(file.getInputStream(), file.getSize(), -1) .contentType(file.getContentType()) .build()); } public InputStream download(String fileName) throws Exception { // 下载文件 return minioClient.getObject(GetObjectArgs.builder() .bucket(bucketName) .object(fileName) .build()); } } ``` 最后,在Controller中使用MinioService处理上传和下载请求: ``` @RestController public class MinioController { @Autowired private MinioService minioService; @PostMapping("/upload") public String upload(@RequestParam("file") MultipartFile[] files) { try { for (MultipartFile file : files) { minioService.upload(file); } return "上传成功"; } catch (Exception e) { e.printStackTrace(); return "上传失败"; } } @GetMapping("/download") public ResponseEntity<InputStreamResource> download(@RequestParam("fileName") String fileName) { try { InputStream inputStream = minioService.download(fileName); InputStreamResource inputStreamResource = new InputStreamResource(inputStream); HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment; filename=" + fileName); return ResponseEntity.ok().headers(headers).contentLength(inputStream.available()) .contentType(MediaType.parseMediaType("application/octet-stream")).body(inputStreamResource); } catch (Exception e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null); } } } ``` 这样,就可以使用Spring BootMinio实现文件批量上传了。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

暮春二十四

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值