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

然后在浏览器上访问接口

就达到这个预览的效果了

相关推荐
要加油哦~几秒前
JS | 知识点总结 - 原型链
开发语言·javascript·原型模式
鄃鳕17 分钟前
python迭代器解包【python】
开发语言·python
new coder18 分钟前
[c++语法学习]Day10:c++引用
开发语言·c++·学习
驰羽24 分钟前
[GO]GORM 常用 Tag 速查手册
开发语言·后端·golang
Narcissiffo33 分钟前
【C语言】str系列函数
c语言·开发语言
楚韵天工33 分钟前
宠物服务平台(程序+文档)
java·网络·数据库·spring cloud·编辑器·intellij-idea·宠物
helloworddm35 分钟前
Orleans Stream SubscriptionId 生成机制详解
java·系统架构·c#
workflower36 分钟前
软件工程与计算机科学的关系
开发语言·软件工程·团队开发·需求分析·个人开发·结对编程
失散1338 分钟前
分布式专题——43 ElasticSearch概述
java·分布式·elasticsearch·架构
ajsbxi39 分钟前
【Java 基础】核心知识点梳理
java·开发语言·笔记