java springboot2.7 写一个本地 pdf 预览的接口

依赖方面 创建的是 接口web项目就好了

然后包管理工具打开需要这些

java 复制代码
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

然后 例如这里我要预览 本地 E盘下的 ydzxmgf下的git分支管理规范.pdf文件 就可以这样写

java 复制代码
@GetMapping("/pdf")
    public ResponseEntity<Resource> previewPdfFile() throws IOException {
        // 指定文件路径
        String filePath = "E:/ydzxmgf/git分支管理规范.pdf";

        // 创建文件资源
        File file = new File(filePath);
        Path path = Paths.get(file.getAbsolutePath());
        Resource resource = new FileSystemResource(file);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=" + file.getName());
        headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_PDF_VALUE);

        // 返回响应实体
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.APPLICATION_PDF)
                .body(resource);
    }

然后在浏览器上访问接口

就达到这个预览的效果了

相关推荐
bush42 分钟前
嵌入式linux学习记录十二,mmap
java·linux·学习
luj_17685 分钟前
残熵算法:风险缓冲与效率优化的融合
c语言·开发语言·网络·经验分享·算法
源码宝6 分钟前
基于SpringCloud+UniApp的智慧工地云平台整体架构设计与实现
java·人工智能·spring cloud·源码·智慧工地·云平台
Legendary_00823 分钟前
从 DC 圆口到 USB-C PD:LED 照明设备的供电升级逻辑
c语言·开发语言
SilentSamsara25 分钟前
Python 微服务全链路:gRPC + 链路追踪 + 服务网格接入
开发语言·分布式·python·微服务·架构
一只积极向上的小咸鱼26 分钟前
VS Code / Warp MCP 迁移到 Codex MCP 配置总结
开发语言
天文家40 分钟前
深入理解装饰器与适配器:从设计模式到 Spring AOP 的工程实践
java·设计模式
贺国亚44 分钟前
Spring-AI与LangChain4j
java·人工智能·spring
Cloud_Shy6181 小时前
解读《Effective Python 3rd Edition》:从练气到老魔(第三章 Item 21 - 24)
开发语言·人工智能·笔记·python·迭代器模式
多彩电脑1 小时前
Lua中的元表里的__index和__newindex
开发语言·lua