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);
    }
}
相关推荐
Mem0rin几秒前
[Java/数据结构]线性表之栈与队列
java·开发语言·数据结构
东离与糖宝9 分钟前
告别Python!Java本地部署Gemma 4:Maven一键集成
java·人工智能
吃不胖爹10 分钟前
idea低版本用高版本的jdk
java·ide·intellij-idea
程序员榴莲13 分钟前
JVM体系结构(运行时数据区)初解
java·jvm
DFT计算杂谈15 分钟前
eDMFT安装教程
java·服务器·前端·python·算法
云烟成雨TD17 分钟前
Spring AI 1.x 系列【23】:工具配置详解(全局默认+运行时动态)
人工智能·python·spring
遇见你...19 分钟前
A02 Spring-IOC和DI注解开发
数据库·spring·sqlserver
hunter19901020 分钟前
java开发学习阶段
java
Dxy123931021621 分钟前
Python图片转PDF:高效实现多图合并与自定义布局
java·python·pdf
okiseethenwhat23 分钟前
冒泡排序的面试话术和写法解析
java