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

发布于:2025-08-10 ⋅ 阅读:(24) ⋅ 点赞:(0)

引入依赖

  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;
    @Bean
    public 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 {
    @Autowired
    private MinioClient minioClient;
    @Value("${minio.bucket-name}")
    private String bucketName;
    @Autowired
    MinioConfig 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 {
    @Autowired
    private 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)





网站公告

今日签到

点亮在社区的每一天
去签到