开发者

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

开发者 https://www.devze.com 2024-09-24 10:38 出处:网络 作者: jew_朱文斌
目录前言项目结构1. 添加依赖2. 配置 MinIO3. 创建 MinioConfig4. 创建 FileEntity5. 创建 FileRepository6. 创建 FileService7. 创建 FileServiceImpl8. 创建 FileController9. 主应用程序类总结前言
目录
  • 前言
  • 项目结构
  • 1. 添加依赖
  • 2. 配置 MinIO
  • 3. 创建 MinioConfig
  • 4. 创建 FileEntity
  • 5. 创建 FileRepository
  • 6. 创建 FileService
  • 7. 创建 FileServiceImpl
  • 8. 创建 FileController
  • 9. 主应用程序类
  • 总结

前言

下面是一个完整的示例,展示如何使用 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.mowww.devze.comdel.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 IOExceppythontion {
        String fileName = file.getOriginalFilename();
        try {
            minioClient.putObject(
                    bucketName,
                    fileName,
                    file.getInputStream(),
                    file.getContentType()
            );
            String fileUrl = minioClient.getObjectUrl(bucketName, fileName);

            FileEntity www.devze.comfileEntity = new FileEntity();
            fileEntity.setFileName(fileName);
            fileEn编程客栈tity.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
    priwww.devze.comvate 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上传下载文件内容请搜索编程客栈(www.devze.com)以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程客栈(www.devze.com)!

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号