spring boot 返回文件流

所需依赖

java 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

完整的Controller代码

java 复制代码
import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@Controller
public class FileDownloadController {

    @GetMapping("/download")
    @ResponseBody
    public ResponseEntity<InputStreamResource> downloadFile() throws IOException {
        File file = new File("实际的文件路径");
        InputStream inputStream = new FileInputStream(file);
        InputStreamResource resource = new InputStreamResource(inputStream);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=实际的文件名");

        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }
}
相关推荐
两个蝴蝶飞4 小时前
Java量化系列(四):实现自选股票维护功能
java·经验分享
短剑重铸之日6 小时前
7天读懂MySQL|Day 5:执行引擎与SQL优化
java·数据库·sql·mysql·架构
酒九鸠玖6 小时前
Java--多线程
java
Dreamboat-L6 小时前
云服务器上部署nginx
java·服务器·nginx
长安er7 小时前
LeetCode215/347/295 堆相关理论与题目
java·数据结构·算法·leetcode·
cici158747 小时前
C#实现三菱PLC通信
java·网络·c#
k***92169 小时前
【C++】继承和多态扩展学习
java·c++·学习
weixin_440730509 小时前
java结构语句学习
java·开发语言·学习
JIngJaneIL9 小时前
基于java+ vue医院管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
Coder_Boy_9 小时前
Spring AI 源码大白话解析
java·人工智能·spring