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

然后在浏览器上访问接口

就达到这个预览的效果了

相关推荐
小杍随笔7 分钟前
【Rust 语言编程知识与应用:基础数据类型详解】
开发语言·后端·rust
Yupureki13 分钟前
《MySQL数据库基础》1. 数据库基础
c语言·开发语言·数据库·c++·mysql·oracle·github
杰克尼24 分钟前
苍穹外卖--day08
java·数据库·spring boot·mybatis·notepad++
enmouhuadou41 分钟前
快速运行matlab仿真方法
开发语言·matlab
lierenvip43 分钟前
SQL 建表语句详解
java·数据库·sql
kuntli1 小时前
Spring Bean生命周期全解析
java
ok_hahaha1 小时前
java从头开始-苍穹外卖-day06-微信小程序开发-微信登录和商品浏览
java·微信·微信小程序·小程序
m0_706653231 小时前
使用C-Free进行浮点变量的四则运算指南
c语言·开发语言
Java面试题总结1 小时前
Spring @Validated失效?原因、排查与高效解决方案全解析
java·spring boot·spring
剑锋所指,所向披靡!1 小时前
MySQL数据的增删改查
java·数据库·mysql