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);
    }
}
相关推荐
java小白小4 小时前
SpringBoot(01): 初识SpringBoot,从Spring的痛点说起
spring boot
用户128526116027 小时前
我把祖传Java项目重构后,接口响应从3s砍到了200ms,只改了这几行代码
java
Linsk7 小时前
组件 = 模板 + 业务逻辑
java·前端·vue.js
星沉远浦8 小时前
用Gemini高效解决Java代码报错难以定位的问题
java
用户31693538118311 小时前
如何从零编写一个 Spring Boot Starter
spring boot
用户2986985301412 小时前
Word 文档字符级格式化:Java 实现方案详解
java·后端
笨鸟飞不快12 小时前
从单个服务到集群:一次完整的性能排查复盘
java·前端
荣码12 小时前
用Streamlit给AI应用套个界面,10行代码出Web页面
java·python
SamDeepThinking12 小时前
Java微服务练习方式
java·后端·微服务
朦胧之1 天前
AI 编程-老项目改造篇
java·前端·后端