当前位置:首页 » 《关于电脑》 » 正文

java 使用minio上传下载文件(完整版)

23 人参与  2024年10月22日 15:21  分类 : 《关于电脑》  评论

点击全文阅读


下面是一个完整的示例,展示如何使用 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:9000minio.access-key=minioadminminio.secret-key=minioadminminio.bucket-name=mybucketspring.datasource.url=jdbc:h2:mem:testdbspring.datasource.driverClassName=org.h2.Driverspring.datasource.username=saspring.datasource.password=passwordspring.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;@Configurationpublic 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;@Entitypublic 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;@Servicepublic 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;@SpringBootApplicationpublic class Application {    public static void main(String[] args) {        SpringApplication.run(Application.class, args);    }}

总结

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


点击全文阅读


本文链接:http://zhangshiyu.com/post/175547.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1