当前位置: 首页 > article >正文

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

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

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

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文件 就可以这样写

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

然后在浏览器上访问接口
在这里插入图片描述
就达到这个预览的效果了


http://www.kler.cn/a/105247.html

相关文章:

  • 八大排序算法(C语言版)之插入排序
  • HTTP 协议参考文档
  • http代理IP它有哪些应用场景?如何提升访问速度?
  • 使用ruoyi框架遇到的问题修改记录
  • 8位机adc采样正弦波频率
  • 管理员|顾问必看!8个Salesforce权限集的最佳实践
  • Simulation Studio - TRNSYS
  • 后端接口返回常见的状态码
  • vue2 系列:自定义 v-model
  • 【机器学习合集】激活函数合集 ->(个人学习记录笔记)
  • 文件上传漏洞(1), 文件上传绕过原理
  • php-手动搭建windows的php和nginx、phpmyadmin环境
  • uniapp把文件中的内复制到另一个文件中
  • 数据清洗与规范化详解
  • 分布式事务——CAP理论 解决分布式事务的思路 Seata组件初识 和 部署
  • linux实现基础网络库(socket,epoll,pthread,cmake,pipe, sem,codition,)
  • 一台服务器最大能支持多少条 TCP 连接
  • nginx负载均衡配置
  • 逐字稿 | 视频理解论文串讲(下)【论文精读】
  • 【数据结构】ST 表与 RMQ 算法