当前位置:首页 » 《随便一记》 » 正文

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

16 人参与  2024年04月16日 13:05  分类 : 《随便一记》  评论

点击全文阅读


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 = "上传文件")@RestControllerpublic 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;@Servicepublic 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;@Componentpublic 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;    }}

之后发送请求

在这里插入图片描述


点击全文阅读


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

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

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

最新文章

  • ⽗亲被欺辱后,我为他洗冤翻盘全文阅读_奶奶孙子麦芽糖独家首发_小说后续在线阅读_无删减免费完结_
  • 俞晓小说完结篇(豪门骗嫁:腹黑总裁步步谋婚)章节前文+全篇阅读(俞晓)最近更新
  • 手撕冒充我身份抢拉布布的第三者故事会_老公赵桐州陆雅宁免费阅读_小说后续在线阅读_无删减免费完结_
  • 以前不喜欢的人,以后也不会喜欢全文免费阅读无弹窗大结局_林雨浔楚淮晏最新章节列表_笔趣阁(以前不喜欢的人,以后也不会喜欢:完结+结局+番外)
  • 救命血被抽干,中了绝情蛊的老公弟弟双双傻眼了免费赏析_弟弟月儿谢总全文+后续_小说后续在线阅读_无删减免费完结_
  • 愿意季清涟小说番外+结局(心上音)小说在线阅读
  • 莫斯科没有眼泪好评_林陌瑾修许青青后续+完结_小说后续在线阅读_无删减免费完结_
  • 宠妻上瘾:霸道老公坏死了(秦慕辰苏莫浅)整本+后续+(宠妻上瘾:霸道老公坏死了)结局在线阅读
  • 林雨浔楚淮晏:+后续+番外以前不喜欢的人,以后也不会喜欢无删减小说在线无广告高口碑小说
  • (凌烬寒戚无筝)她见过他爱过的模样小说最终篇章章节在线无广告高口碑小说
  • 小说宋可清(宋可清)已更新+无删减(完蛋!我把反派大佬撩红温了)
  • 唐圆圆小说(七十年代养娃后成为对照组)起点章节+全篇阅读热门作品预订

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

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