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);
    }
}
相关推荐
荒古前25 分钟前
Spring Boot + MyBatis 启动报错:不允许有匹配 “[xX][mM][lL]“ 的处理指令目标
spring boot·后端·mybatis
mldlds25 分钟前
Spring Boot 实战:轻松实现文件上传与下载功能
java·数据库·spring boot
xxjj998a31 分钟前
Spring Boot 整合 Apollo 配置中心实战
java·spring boot·后端
武超杰44 分钟前
Spring 纯注解配置全解析(进阶版)
java·开发语言
AC赳赳老秦1 小时前
OpenClaw关键词挖掘Agent配置(附SOP脚本,可直接复制使用)
java·大数据·开发语言·人工智能·python·pygame·openclaw
splage1 小时前
SpringBoot 与 SpringCloud的版本对应详细版
spring boot·后端·spring cloud
茶本无香1 小时前
JDK 21 ZGC分代功能详解:配置、原理及生产环境实践
java·jvm
xxjj998a1 小时前
SpringBoot3.3.0集成Knife4j4.5.0实战
java
wellc1 小时前
Spring Boot 热部署
java·spring boot·后端
金銀銅鐵2 小时前
[Java] 从 class 文件看动态代理
java·后端