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);
    }
}
相关推荐
Hx_Ma163 小时前
SpringMVC框架提供的转发和重定向
java·开发语言·servlet
期待のcode4 小时前
原子操作类LongAdder
java·开发语言
舟舟亢亢5 小时前
Java集合笔记总结
java·笔记
小酒窝.5 小时前
【多线程】多线程打印ABC
java
乡野码圣5 小时前
【RK3588 Android12】RCU机制
java·jvm·数据库
JAVA+C语言5 小时前
如何优化 Java 多主机通信的性能?
java·开发语言·php
编程彩机7 小时前
互联网大厂Java面试:从分布式架构到大数据场景解析
java·大数据·微服务·spark·kafka·分布式事务·分布式架构
小酒窝.7 小时前
【多线程】多线程打印1~100
java·多线程
君爱学习7 小时前
基于SpringBoot的选课调查系统
java
APIshop7 小时前
Java 实战:调用 item_search_tmall 按关键词搜索天猫商品
java·开发语言·数据库