java使用minio上传下载文件完整版教程

 更新时间:2024年09月24日 09:47:54   作者:jew_朱文斌  
本示例教程介绍了如何使用SpringBoot框架结合MinIO服务实现文件的上传和下载功能,并将文件信息存储在数据库的file表中,文中通过代码介绍的非常详细,需要的朋友可以参考下

前言

下面是一个完整的示例,展示如何使用 MinIO 上传和下载文件,并将文件信息存储到数据库中的 file 表。我们将使用 Spring Boot 框架来实现这个功能。

项目结构

src
├── main
│   ├── java
│   │   └── com
│   │       └── example
│   │           ├── controller
│   │           │   └── FileController.java
│   │           ├── service
│   │           │   ├── FileService.java
│   │           │   └── FileServiceImpl.java
│   │           ├── repository
│   │           │   └── FileRepository.java
│   │           ├── model
│   │           │   └── FileEntity.java
│   │           ├── config
│   │           │   └── MinioConfig.java
│   │           └── Application.java
│   └── resources
│       └── application.properties

1. 添加依赖

在 pom.xml 中添加必要的依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>io.minio</groupId>
        <artifactId>minio</artifactId>
        <version>8.3.0</version>
    </dependency>
    <dependency>
        <groupId>com.h2database</groupId>
        <artifactId>h2</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
</dependencies>

2. 配置 MinIO

在 application.properties 中添加 MinIO 配置信息:

minio.url=http://localhost:9000
minio.access-key=minioadmin
minio.secret-key=minioadmin
minio.bucket-name=mybucket

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

3. 创建 MinioConfig

package com.example.config;

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 minioAccessKey;

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

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

4. 创建 FileEntity

package com.example.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;

@Entity
public class FileEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String fileName;
    private String fileUrl;

    // Getters and Setters
}

5. 创建 FileRepository

package com.example.repository;

import com.example.model.FileEntity;
import org.springframework.data.jpa.repository.JpaRepository;

public interface FileRepository extends JpaRepository<FileEntity, Long> {
}

6. 创建 FileService

package com.example.service;

import com.example.model.FileEntity;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

public interface FileService {
    FileEntity uploadFile(MultipartFile file) throws IOException;
    byte[] downloadFile(String fileName) throws Exception;
}

7. 创建 FileServiceImpl

package com.example.service;

import com.example.model.FileEntity;
import com.example.repository.FileRepository;
import io.minio.MinioClient;
import io.minio.errors.MinioException;
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.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private MinioClient minioClient;

    @Autowired
    private FileRepository fileRepository;

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

    @Override
    public FileEntity uploadFile(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        try {
            minioClient.putObject(
                    bucketName,
                    fileName,
                    file.getInputStream(),
                    file.getContentType()
            );
            String fileUrl = minioClient.getObjectUrl(bucketName, fileName);

            FileEntity fileEntity = new FileEntity();
            fileEntity.setFileName(fileName);
            fileEntity.setFileUrl(fileUrl);

            return fileRepository.save(fileEntity);
        } catch (MinioException e) {
            throw new IOException("Error occurred while uploading file to MinIO", e);
        }
    }

    @Override
    public byte[] downloadFile(String fileName) throws Exception {
        try (InputStream stream = minioClient.getObject(bucketName, fileName);
             ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {

            byte[] buffer = new byte[1024];
            int length;
            while ((length = stream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, length);
            }
            return outputStream.toByteArray();
        } catch (MinioException e) {
            throw new Exception("Error occurred while downloading file from MinIO", e);
        }
    }
}

8. 创建 FileController

package com.example.controller;

import com.example.model.FileEntity;
import com.example.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/files")
public class FileController {

    @Autowired
    private FileService fileService;

    @PostMapping("/upload")
    public ResponseEntity<FileEntity> uploadFile(@RequestParam("file") MultipartFile file) throws IOException {
        FileEntity fileEntity = fileService.uploadFile(file);
        return ResponseEntity.ok(fileEntity);
    }

    @GetMapping("/download/{fileName}")
    public ResponseEntity<byte[]> downloadFile(@PathVariable String fileName) throws Exception {
        byte[] data = fileService.downloadFile(fileName);
        return ResponseEntity.ok()
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"")
                .body(data);
    }
}

9. 主应用程序类

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

总结

通过上述步骤,我们创建了一个完整的 Spring Boot 应用程序,它使用 MinIO 上传和下载文件,并将文件信息存储到数据库中的 file 表。你可以通过 /files/upload 接口上传文件,通过 /files/download/{fileName} 接口下载文件。

到此这篇关于java使用minio上传下载文件的文章就介绍到这了,更多相关java用minio上传下载文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Java并发系列之AbstractQueuedSynchronizer源码分析(共享模式)

    Java并发系列之AbstractQueuedSynchronizer源码分析(共享模式)

    这篇文章主要为大家详细介绍了Java并发系列之AbstractQueuedSynchronizer源码,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-02-02
  • Java项目工程代码深度刨析总结

    Java项目工程代码深度刨析总结

    一个项目工程里的代码是怎样的呢?对于初学者或者没有参与过项目的零经验同学这都是未知且让人好奇的,本篇文章带你一探究竟,踏入真实项目的大门
    2022-08-08
  • Spring中容器创建的四种方式示例

    Spring中容器创建的四种方式示例

    这篇文章主要介绍了Spring中容器创建的四种方式示例,Spring容器是Spring框架的核心部分,它负责管理和组织应用程序中的对象,它提供了一种轻量级的、非侵入式的方式来实现对象的创建、依赖注入和生命周期管理,需要的朋友可以参考下
    2023-10-10
  • java 四舍五入使java保留2位小数示例讲解

    java 四舍五入使java保留2位小数示例讲解

    这篇文章主要介绍了java四舍五入使java保留2位小数示例,大家参考使用
    2013-12-12
  • spring-boot 禁用swagger的方法

    spring-boot 禁用swagger的方法

    本篇文章主要介绍了spring-boot 禁用swagger的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-02-02
  • Java实现的zip工具类完整实例

    Java实现的zip工具类完整实例

    这篇文章主要介绍了Java实现的zip工具类,结合完整实例形式分析了Java针对zip文件指定路径压缩、递归压缩等相关操作技巧,需要的朋友可以参考下
    2018-12-12
  • IDEA Eval Reset 使用方法汇总

    IDEA Eval Reset 使用方法汇总

    本文给大家介绍了IDEA Eval Reset 使用方法,安装插件包括离线安装方式和在线安装方式,本文给大家介绍的非常详细,感兴趣的朋友跟随小编一起看看吧
    2023-10-10
  • Java PriorityQueue优点和缺点面试精讲

    Java PriorityQueue优点和缺点面试精讲

    这篇文章主要为大家介绍了Java面试中PriorityQueue的优点和缺点及使用注意详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-10-10
  • 使用Runnable实现数据共享

    使用Runnable实现数据共享

    这篇文章主要为大家详细介绍了如何使用Runnable实现数据共享,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-07-07
  • Java基础之初识Maven

    Java基础之初识Maven

    这篇文章主要介绍了Java基础之初识Maven,文中有非常详细的代码示例,对正在学习java基础的小伙伴们有非常好的帮助,需要的朋友可以参考下
    2021-05-05

最新评论