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

然后在浏览器上访问接口

就达到这个预览的效果了

相关推荐
Acrelhuang1 分钟前
小小电能表,如何撬动家庭能源革命?
java·大数据·开发语言·人工智能·物联网
jyd01248 分钟前
MongoDB 与 Java 实体类型 LocalTime 时区转换问题解决方案
java·数据库·mongodb
头发还没掉光光10 分钟前
Linux网络初始及网络通信基本原理
linux·运维·开发语言·网络·c++
疏狂难除10 分钟前
spiderdemo第22题与webassembly的跨域
开发语言·javascript·爬虫·rust·wasm·mitmproxy
WenGyyyL18 分钟前
微信小程序开发——第二章:微信小程序开发环境搭建
开发语言·python·微信小程序
循环过三天22 分钟前
3.2、Python-元组
开发语言·python
一抓掉一大把29 分钟前
RuoYI框架.net版本实现Redis数据隔离
java·开发语言
.格子衫.33 分钟前
Maven高级
java·maven
lkbhua莱克瓦2433 分钟前
Java基础——常用算法4
java·数据结构·笔记·算法·github·排序算法·快速排序
.格子衫.37 分钟前
Maven前奏
java·pycharm·maven