SpringBoot中使用Minio进行图片上传(简单!)

1.启动本地Minio服务

2.打开控制台,获取  accessKey和secretKey

注意:

创建完成后会提示你保存好,一封要保存好!!!!

3.springboot web项目中添加依赖和必要信息

pom文件里添加

<dependency>
    <groupId>io.minio</groupId>
    <artifactId>minio</artifactId>
    <version>8.5.10</version>
 </dependency>

yml文件里添加

spring:
  # 配置文件上传大小限制
  servlet:
    multipart:
      max-file-size: 200MB
      max-request-size: 200MB
minio:
  endpoint: http://localhost:9000
  accessKey: 你的accesskey
  secretKey: 你的secretkry
  bucketName: 你要存文件的桶名

4.定义minio客户端配置类

import io.minio.MinioClient;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Data
@Configuration
public class MinIoClientConfig {
    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${minio.accessKey}")
    private String accessKey;
    @Value("${minio.secretKey}")
    private String secretKey;
    /**
     * 注入minio 客户端
     * @return
     */
    @Bean
    public MinioClient minioClient(){
        return MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
    }
}

5.minio图片上传工具类

import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Component
public class MinioUtils {
    @Autowired
    private MinioClient minioClient;
    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${minio.bucketName}")
    private String bucketName;

    public String upload(MultipartFile file) {
        //获取原文件名
        String fileName = file.getOriginalFilename();
        //定义新文件名
        String NewFileName = "";
        if (fileName != null) {
            //新文件名
            NewFileName = UUID.randomUUID()
                    + fileName.substring(fileName.lastIndexOf("."));
        }
        try {
            InputStream in = file.getInputStream();
            minioClient.putObject(PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(NewFileName)//用新文件名存入
                    .stream(in, in.available(), -1)
                    .contentType(file.getContentType())
                    .build());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return endpoint + "/" + bucketName + "/" + NewFileName;//返回访问的路径
    }
}

6.编写控制器Controller

@Slf4j
@RestController
public class UploadController {

    @Autowired
    private MinioUtils minioUtils;

    @PostMapping("/upload")
    public String upload(MultipartFile file) {
        String url = minioUtils.upload(file);
        log.info("上传成功,url:{}", url);
        return url;
    }
}

7.测试

测试成功

复制路径到浏览器

返回控制台,刚刚上传的图片也已经过来了

  • 5
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面给你提供一个完整的在 Spring Boot 使用 MinIO 进行文件上传和下载的示例代码。 1. 添加 MinIO 的依赖 在 pom.xml 文件添加 MinIO 的依赖: ```xml <dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>7.0.2</version> </dependency> ``` 2. 配置 MinIO 的连接信息 在 application.yml 或 application.properties 文件添加 MinIO 的连接信息,例如: ```yaml spring: cloud: minio: endpoint: http://localhost:9000 access-key: ACCESS-KEY secret-key: SECRET-KEY ``` 3. 编写 MinIO 的代码 ```java @Service public class MinioService { @Autowired private MinioClient minioClient; public void uploadFile(String bucketName, String fileName, InputStream inputStream) throws Exception { minioClient.putObject(PutObjectArgs.builder() .bucket(bucketName) .object(fileName) .stream(inputStream, inputStream.available(), -1) .build()); } public InputStream downloadFile(String bucketName, String fileName) throws Exception { return minioClient.getObject(GetObjectArgs.builder() .bucket(bucketName) .object(fileName) .build()); } } ``` 以上代码实现了上传和下载文件的功能。 4. 编写 Controller 层代码 ```java @RestController @RequestMapping("/file") public class FileController { @Autowired private MinioService minioService; /** * 上传文件 */ @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) throws Exception { if (file.isEmpty()) { return "上传失败,请选择文件"; } String bucketName = "test-bucket"; String fileName = file.getOriginalFilename(); InputStream inputStream = file.getInputStream(); minioService.uploadFile(bucketName, fileName, inputStream); return "上传成功"; } /** * 下载文件 */ @GetMapping("/download") public ResponseEntity<byte[]> downloadFile(@RequestParam("fileName") String fileName) throws Exception { String bucketName = "test-bucket"; InputStream inputStream = minioService.downloadFile(bucketName, fileName); byte[] bytes = IOUtils.toByteArray(inputStream); HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); headers.setContentDispositionFormData("attachment", fileName); return new ResponseEntity<>(bytes, headers, HttpStatus.OK); } } ``` 以上代码实现了上传和下载文件的接口。 5. 运行代码 运行 Spring Boot 项目,测试 MinIO 的上传和下载功能。 以上就是在 Spring Boot 使用 MinIO 进行文件上传和下载的全部内容,希望能对你有所帮助。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值