Spring Boot integrates MinIO to implement file upload, download and deletion

MinIO is an open source object storage service built on a cloud-native architecture and provides a high-performance, easily scalable and secure storage solution.

1. Install and configure MinIO server

For the convenience of demonstration, this article uses Windows installation 

1. Download the MinIO installation file from the official website, address: https://dl.minio.org.cn/server/minio/release/windows-amd64/minio.exe

2. Create the start.bat configuration startup file in the minio.exe directory: "D:\Java\MinIo" is the location where the file is stored when the service is started. 

minio.exe server D:\Java\MinIo

3. Double-click the minio.exe file to start

 

4. Create a Spring Boot project

        1. Create a Spring Boot project

        2. Add dependencies and pay attention to dependency versions

<!--文件上传-->
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.4</version>
</dependency>

<!--MinIO对象存储-->
<dependency>
    <groupId>io.minio</groupId>
    <artifactId>minio</artifactId>
    <version>8.4.3</version>
</dependency>
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>4.8.1</version>
</dependency>

2. Configuration file

        1.yaml configuration file

#MinIO配置
minio:
  endpoint: http://127.0.0.01:9000 #连接地址
  accessKey: minioadmin#账号 默认minioadmin
  secretKey: minioadmin#密码 默认minioadmin
  bucketName: contractfile #桶名 存放合同文件 桶名校验规则:!name.matches("^[a-z0-9][a-z0-9\\.\\-]+[a-z0-9]$")

         2. Configuration class, used to connect to Minio

@Data
@Configuration
@ConfigurationProperties(prefix = "minio")
public class MinioConfig {

    //连接地址
    private String endpoint;

    //账号 默认minioadmin
    private String accessKey;

    //密码 默认minioadmin
    private String secretKey;

    @Bean
    public MinioClient minioClient() {
        MinioClient minioClient = MinioClient.builder()
                .endpoint(endpoint)
                .credentials(accessKey, secretKey)
                .build();
        return minioClient;
    }

}

        3. Tool class, used to operate files

@Slf4j
@Component
public class MinioUtils {

    @Autowired
    private MinioClient minioClient;

    @Value("${minio.bucketName}")
    private String bucketName;

    /**
     * 操作文件时先创建Bucket
     * 如果没有Bucket则创建
     *
     * @param bucketName
     */
    @SneakyThrows(Exception.class)
    public void createBucket(String bucketName) {
        if (!bucketExists(bucketName)) {
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
    }

    /**
     * 判断Bucket是否存在,true:存在,false:不存在
     *
     * @param bucketName
     * @return
     */
    @SneakyThrows(Exception.class)
    public boolean bucketExists(String bucketName) {
        return minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
    }


    /**
     * 判断文件是否存在
     *
     * @param bucketName
     * @param fileRealName
     * @return
     */
    public boolean isObjectExist(String bucketName, String fileRealName) {
        boolean exist = true;
        try {
            minioClient.statObject(StatObjectArgs.builder().bucket(bucketName).object(fileRealName).build());
        } catch (Exception e) {
            log.error("[Minio工具类]>>>> 判断文件是否存在, 异常:", e);
            exist = false;
        }
        return exist;
    }

    /**
     * 使用MultipartFile进行文件上传
     *
     * @param bucketName   存储桶
     * @param file         文件
     * @param fileRealName 文件名
     * @return 文件下载外链
     */
    @SneakyThrows(Exception.class)
    public String uploadFile(String bucketName, MultipartFile file, String fileRealName) {
        createBucket(bucketName);
        InputStream inputStream = file.getInputStream();
        minioClient.putObject(
                PutObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileRealName)
                        .contentType(file.getContentType())
                        .stream(inputStream, inputStream.available(), -1)
                        .build());
        GetPresignedObjectUrlArgs args = GetPresignedObjectUrlArgs.builder()
                .bucket(bucketName)
                .object(fileRealName)
                .method(Method.GET).build();
        return minioClient.getPresignedObjectUrl(args);
    }


    /**
     * 删除文件
     *
     * @param bucketName   存储桶
     * @param fileRealName 文件名称
     */
    @SneakyThrows(Exception.class)
    public void removeFile(String bucketName, String fileRealName) {
        createBucket(bucketName);
        minioClient.removeObject(
                RemoveObjectArgs.builder()
                        .bucket(bucketName)
                        .object(fileRealName)
                        .build());
    }

    /**
     * 下载文件
     *
     * @param httpServletResponse httpServletResponse
     * @param fileRealName        文件存储名称
     * @param fileName            文件下载名称
     * @throws IOException IOException
     */
    public void downloadFile(String bucketName, String fileRealName, String fileName, HttpServletResponse httpServletResponse) throws Exception {
        createBucket(bucketName);
        //获取文件流
        InputStream inputStream = minioClient.getObject(GetObjectArgs.builder()
                .bucket(bucketName)
                .object(fileRealName)
                .build());
        //设置响应头信息,告诉前端浏览器下载文件
        httpServletResponse.setContentType("application/octet-stream;charset=UTF-8");
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        //获取输出流进行写入数据
        OutputStream outputStream = httpServletResponse.getOutputStream();
        // 将输入流复制到输出流
        byte[] buffer = new byte[4096];
        int bytesRead = -1;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        // 关闭流资源
        inputStream.close();
        outputStream.close();
    }
}

Guess you like

Origin blog.csdn.net/weixin_58724261/article/details/133313868