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);
    }
}
相关推荐
Metaphor69217 小时前
使用 Python 在 Word 文档中添加、修改和删除变量
python·word
sun032217 小时前
【JDK 动态代理】 和 【CGLIB 代理】对比
java·数据库·sql
文丑颜不良啊17 小时前
LeetCode1261~1280题目解析
java·leetcode
郭小李17 小时前
spring 中的 @EnableWebMvc注解和WebMvcConfigurer接口
java·后端·spring
香蕉大香蕉(06敬畏市场)18 小时前
高频八股 · JVM(8)
java·jvm·面试·八股·大厂实习
养军博客18 小时前
spirngSecurity 鉴权教程02
java·springsecurity
CoderYanger18 小时前
Java EE 进阶:5. Spring IoC&DI(第二弹):Spring IoC
java·开发语言·spring boot·spring·面试·职场和发展·java-ee
aiks_yuan18 小时前
Spring Boot 4 注入 ObjectMapper 报找不到 Bean:升级 Jackson 3 的改法和过渡方案(4.1.2 实测)
spring boot
悟天特斯19 小时前
安防一体化:从“各管各的“到“全局联动“
java·大数据·网络·人工智能·物联网
70后写java的老码农19 小时前
Spring Boot 3.x + ShardingSphere 5.x + MyBatis-Plus 3.x:订单分库分表实战(含两个踩坑记录)
java