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);
    }
}
相关推荐
Moniane15 小时前
时序数据库全面重构指南
java·后端·struts
whm277715 小时前
Visual Basic 值传递与地址传递
java·开发语言·数据结构
没有bug.的程序员16 小时前
云原生与分布式架构的完美融合:从理论到生产实践
java·分布式·微服务·云原生·架构
村口张大爷16 小时前
Spring Boot 初始化钩子
java·spring boot·后端
x_feng_x16 小时前
Java从入门到精通 - 集合框架(二)
java·开发语言·windows
LB211216 小时前
苍穹外卖-缓存套餐 Spring Cache day07
java·spring boot·spring
W.Buffer16 小时前
SpringCloud-Sentinel实战与源码分析:从流量防护到底层实现
spring·spring cloud·sentinel
Le1Yu16 小时前
雪崩问题及其解决方案(请求限流、线程隔离、服务熔断、fallback、sentinel实现以上功能)
java·开发语言
徐子童16 小时前
基于微服务的在线判题系统重点总结
java·微服务·架构
青衫码上行16 小时前
【从0开始学习Java | 第21篇】网络编程综合练习
java·网络·学习