SpringBoot返回InputStream给前端,Java后端返回InputStream给前端,minio使用getObject获取InputStream如何返回给前端

SpringBoot返回InputStream给前端,Java后端返回InputStream给前端,minio使用getObject获取InputStream如何返回给前端

下午在写接口时,一直报错,显示InputStream被关闭,怎么修改都没办法。

在这里插入图片描述

解决方案

如果单纯返回inputStream可以这样

import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/minio")
public class MinioController {

    @Autowired
    private MinioService minioService; // 假设你已经创建了一个 MinioService 类来处理 Minio 操作

    @GetMapping("/file")
    public ResponseEntity<InputStreamResource> getFileFromMinio() {
        InputStream inputStream = minioService.getInputStreamFromMinio(); // 假设这是从 Minio 获取 InputStream 的方法

        // 将 InputStream 转换为 InputStreamResource
        InputStreamResource resource = new InputStreamResource(inputStream);

        // 返回 ResponseEntity 包含 InputStreamResource
        return ResponseEntity.ok()
                .contentLength(inputStream.available())
                .body(resource);
    }
}

普通做法

Minio配置

package com.example.minio.config;

import io.minio.MinioClient;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Data
@Configuration
@ConfigurationProperties(prefix = "minio.config")
public class MinioConfig {
    private String url;
    private String accessKey;
    private String secretKey;

    @Bean
    public MinioClient minioClient() {
        return MinioClient.builder().endpoint(url).credentials(accessKey, secretKey).build();
    }
}

Controller部分

import org.springframework.core.io.InputStreamResource;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/minio")
public class MinioController {

    @Autowired
    private MinioClient minioClient; // 假设你已经创建了一个 MinioService 类来处理 Minio 操作

    @GetMapping("/file")
    public ResponseEntity<InputStreamResource> getFileFromMinio() {
        try (InputStream inputStream = minioClient.getObject(
                GetObjectArgs.builder()
                        .bucket("bunny-test")
                        .object("一颗狼星_许篮心 - 长安忆.mp3")
                        .build())) {

            byte[] content = inputStream.readAllBytes();

            // 返回 ResponseEntity 包含 InputStreamResource
            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + filename)
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .contentLength(content.length)
                    .body(new InputStreamResource(new ByteArrayInputStream(content)));
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    }
}

如果和我一样自己封装的MinIO类可以这样做

Controller

package com.example.minio.controll;

import com.example.minio.service.UploadFIleService;
import io.minio.MinioClient;
import io.minio.errors.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.http.ResponseEntity;
import java.io.*;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;


@Tag(name = "上传文件")
@RestController
public class UploadFileController {
    @Autowired
    private UploadFIleService uploadFIleService;

    @Operation(summary = "获取文件")
    @GetMapping("getFile/{filename}")
    public ResponseEntity<InputStreamResource> getFile(@PathVariable("filename") String filename){
    	 try {
            InputStream inputStream = uploadFIleService.getFile(filename);

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + filename)
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    .contentLength(inputStream.available())
                    .body(new InputStreamResource(inputStream));
        } catch (Exception exception) {
            exception.printStackTrace();
        }

        return null;
    }
}

服务接口实现

package com.example.minio.service.impl;

import com.example.minio.service.UploadFIleService;
import com.example.minio.utils.MinioUtils;
import io.minio.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;

@Service
public class UploadFIleServiceImpl implements UploadFIleService {
    @Autowired
    private MinioUtils minioUtils;

    String bucketName = "bunny-test";// 桶的名称

    // 获取文件
    @Override
    public InputStream getFile(String filename) {
        return minioUtils.getObject(bucketName, filename);
    }
}

MinIO工具类

package com.example.minio.utils;

import io.minio.*;
import io.minio.errors.*;
import io.minio.messages.*;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Map;

@Component
public class MinioUtils {
    @Autowired
    private MinioClient minioClient;

   /**
     * 获取存储桶中的对象锁配置。
     *
     * @param bucketName 桶的名称
     * @return Tags 获取成功不为null
     */
    public ObjectLockConfiguration getObjectLockConfiguration(String bucketName) {
        ObjectLockConfiguration configuration = null;
        try {
            configuration = minioClient.getObjectLockConfiguration(GetObjectLockConfigurationArgs.builder().bucket(bucketName).build());
        } catch (Exception exception) {
            exception.printStackTrace();
        }

        return configuration;
    }
}

之后发送请求

在这里插入图片描述

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot使用MinIO可以通过以下几个步骤: 1. 引入MinIO的依赖:在`pom.xml`文件中添加MinIO的依赖。 ```xml <dependency> <groupId>io.minio</groupId> <artifactId>minio</artifactId> <version>RELEASE.2021-03-03T02-57-17Z</version> </dependency> ``` 2. 配置MinIO连接信息:在`application.properties`或`application.yml`文件中添加MinIO的连接信息。 ```properties # MinIO服务器的连接地址 minio.endpoint=http://localhost:9000 # MinIO服务器的访问密钥 minio.accessKey=minio-access-key # MinIO服务器的访问密钥 minio.secretKey=minio-secret-key ``` ```yaml minio: endpoint: http://localhost:9000 accessKey: minio-access-key secretKey: minio-secret-key ``` 3. 创建MinIO客户端:在Spring Boot的配置类中创建MinIO客户端的Bean。 ```java 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.endpoint}") private String endpoint; @Value("${minio.accessKey}") private String accessKey; @Value("${minio.secretKey}") private String secretKey; @Bean public MinioClient minioClient() { return MinioClient.builder() .endpoint(endpoint) .credentials(accessKey, secretKey) .build(); } } ``` 4. 使用MinIO进行文件上传和下载:在需要使用MinIO的地方注入MinIO客户端,然后使用MinIO客户端的方法进行文件上传和下载操作。 ```java import io.minio.MinioClient; import io.minio.UploadObjectArgs; import io.minio.GetObjectArgs; @Service public class MinioService { private final MinioClient minioClient; public MinioService(MinioClient minioClient) { this.minioClient = minioClient; } public void uploadFile(String bucketName, String objectName, InputStream inputStream, long size, String contentType) throws Exception { minioClient.uploadObject( UploadObjectArgs.builder() .bucket(bucketName) .object(objectName) .stream(inputStream, size, -1) .contentType(contentType) .build()); } public InputStream downloadFile(String bucketName, String objectName) throws Exception { return minioClient.getObject( GetObjectArgs.builder() .bucket(bucketName) .object(objectName) .build()); } // 其他操作... } ``` 这样就可以在Spring Boot使用MinIO进行文件的上传和下载了。你可以根据具体的需求,进一步扩展MinIO的功能,例如创建、删除、列举存储桶等操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值