Springboot 项目下载资源目录下的 Word 文件

java 复制代码
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.InputStreamResource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FileController {

    private final ResourceLoader resourceLoader;

    @Autowired
    public FileController(ResourceLoader resourceLoader) {
        this.resourceLoader = resourceLoader;
    }

    @GetMapping("/downloadWord")
    public ResponseEntity<InputStreamResource> downloadWord() throws IOException {
        Resource resource = resourceLoader.getResource("classpath:templates/word.docx");
        InputStream inputStream = resource.getInputStream();
        InputStreamResource inputStreamResource = new InputStreamResource(inputStream);

        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=word.docx");

        return ResponseEntity.ok()
                .headers(headers)
                .contentType(MediaType.parseMediaType("application/msword"))
                .body(inputStreamResource);
    }
}
相关推荐
期待のcode35 分钟前
Spring框架1—Spring的IOC核心技术1
java·后端·spring·架构
鼠鼠我捏,要死了捏39 分钟前
Spring Boot Actuator自定义指标与监控实践指南
spring boot·监控·actuator
葵野寺43 分钟前
【RelayMQ】基于 Java 实现轻量级消息队列(七)
java·开发语言·网络·rabbitmq·java-rabbitmq
书院门前细致的苹果1 小时前
JVM 全面详解:深入理解 Java 的核心运行机制
java·jvm
上官浩仁1 小时前
springboot excel 表格入门与实战
java·spring boot·excel
Hello.Reader2 小时前
从零到一上手 Protocol Buffers用 C# 打造可演进的通讯录
java·linux·c#
树码小子3 小时前
Java网络初识(4):网络数据通信的基本流程 -- 封装
java·网络
稻草人想看远方3 小时前
GC垃圾回收
java·开发语言·jvm
en-route3 小时前
如何在 Spring Boot 中指定不同的配置文件?
java·spring boot·后端
百锦再4 小时前
在 CentOS 系统上实现定时执行 Python 邮件发送任务
java·linux·开发语言·人工智能·python·centos·pygame