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);
    }
}
相关推荐
无名-CODING5 小时前
栈与队列学习笔记
java·笔记
Hui Baby5 小时前
LSM 原理、实现及与 B+ 树的核心区别
java·linux·算法
NZT-485 小时前
C++基础笔记(二)队列deque,queue和堆priority_queue
java·c++·笔记
Tadas-Gao5 小时前
存储技术革命:SSD、PCIe与NVMe的创新架构设计与性能优化
java·性能优化·架构·系统架构·存储
codergjw5 小时前
常见面试题
java
咕噜企业分发小米5 小时前
如何平衡服务器内存使用率和系统稳定性?
java·服务器·前端
李子园的李5 小时前
函数式编程与传统编程的对比——基于java
java
爬山算法5 小时前
Netty(13)Netty中的事件和回调机制
java·前端·算法
南极企鹅5 小时前
Gson转义特殊字符
java