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;
    }
}

之后发送请求

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值