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);
    }

然后在浏览器上访问接口

就达到这个预览的效果了

相关推荐
超梦dasgg14 分钟前
Java 生产环境 MQ 技术选型全解析
java·开发语言·java-rocketmq·java-rabbitmq
霸道流氓气质14 分钟前
Spring AI 多工具链式调用(Tool Chain)极简实战
java·人工智能·spring
罗超驿1 小时前
22.深入剖析JDBC架构:从原生API到企业级数据交互核心
java·数据库·mysql·面试
桀人1 小时前
C++——模板初阶(收录在专栏C++入门到精通)
开发语言·c++
一直有一个ac的梦想1 小时前
cmu15445 2025fall lec 18 transactions with two-phase lock
java·开发语言·数据库
九皇叔叔1 小时前
Spring-Ai-Alibaba [04] 04-llm-platform-custom-demo
java·人工智能·spring
技术路上的探险家1 小时前
Sa-Token 单点登录(SSO)三种模式大白话详解:告别重复登录
java·sa-token·单点登录·sso
JAVA社区1 小时前
Java进阶全套教程(四)—— SpringMVC框架详解
java·开发语言·spring·面试·职场和发展
ㄣ知冷煖★1 小时前
统一网关架构实践:从 Token 鉴权到路由、策略与凭证池转发全链路解析
java·服务器·架构