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);
    }
}
相关推荐
纪莫几秒前
技术面:Spring (事务传播机制、事务失效的原因、BeanFactory和FactoryBean的关系)
java·spring·java面试⑧股
红衣小蛇妖21 分钟前
LeetCode-704-二分查找
java·算法·leetcode·职场和发展
!chen23 分钟前
【Spring Boot】自定义starter
java·数据库·spring boot
koko4237 分钟前
天津小公司面经
java·学习·面试
zjjuejin1 小时前
Maven 现代开发流程的集成
java·后端·maven
MK4221 小时前
Word卡顿,过很久才弹窗网络连接失败解决办法
word·word卡顿·officeplus·网络连接失败
Zzzzmo_1 小时前
【Java】杨辉三角、洗牌算法
java·数据结构·算法
码界奇点1 小时前
基于飞算JavaAI的在线图书借阅平台从设计到实现的完整指南
java·飞书
QiZhang | UESTC1 小时前
JAVA算法练习题day27
java·开发语言·c++·算法·leetcode·hot100
hrrrrb1 小时前
【Spring Boot】Spring Boot 中常见的加密方案
java·spring boot·后端