java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > java用minio上传下载文件

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

作者: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上传下载文件内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文