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

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

0 人参与  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