实现在线查看pdf文件(Java前后端代码)

1.引入pdfJs

下载pdfJs

 点击Download

下载到本地是一个zip文件,在项目中建立一个pdfJs文件夹,将解压的文件全部拷贝至这个文件夹,

好,接下来是代码:

 //根据项目id查看合同
    @ResponseBody
    @GetMapping("/selProjectImgById")
    public void selProjectImgById(Long projectId,HttpServletRequest request, HttpServletResponse response) throws IOException {
        System.out.println("查看合同");
        ProjectInfo one = projectInfoService.getOne(new QueryWrapper<ProjectInfo>().eq("PROJECT_ID", projectId).select("PROJECT_TRACT_IMG","PROJECT_NAME"));
        byte[] projectTractImg = one.getProjectTractImg();

        response.setContentType("application/octet-stream");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + one.getProjectName()+".pdf");

        byte[] buff = new byte[1024];
        BufferedInputStream bis = null;
        OutputStream os = null;
        try {
            System.out.println("==================pdf处理开始==================");
            os = response.getOutputStream();
            //获得PDF文件流,核心代码
            InputStream is = new ByteArrayInputStream(projectTractImg);
            System.out.println("获取流结束。。。。");
            bis = new BufferedInputStream(is);

            int i = 0;
            while ((i = bis.read(buff)) != -1) {
                os.write(buff, 0, i);
                os.flush();

            }

        } catch (Exception e) {
            System.out.println("pdf处理出现异常:" + e.getMessage() + "; ");
        } finally {
            try {
                bis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }



    }

前端:

 //点击查看合同按钮
        $("#projectTractImg").click(function (){
            layer.msg("请稍等")
            window.open("${pageContext.request.contextPath}/js/pdfJs/web/viewer.html?file="
                +encodeURIComponent("${pageContext.request.contextPath}/projectInfo/selProjectImgById?projectId="+ project.projectId +""));
        })

前端代码释义:

window.open:打开新窗口
"${pageContext.request.contextPath}/js/pdfJs/web/viewer.html?file=",此路径就是下载的pdfJs的一个静态页面,file是我们从后端查询出来的pdf的二进制数据,所有后面的路径就是给后端发送请求获取数据

最终效果:

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Spring Boot 和 Vue 前后端分离架构中,实现文件预览可以通过前端发送请求获取文件的 URL,然后在前端使用相关插件或组件进行文件预览。 下面是一种可能的实现方式: 1. 后端实现: - 在 Spring Boot 中配置静态资源路径,将存储文件文件夹路径设置为静态资源路径。例如,可以在 `application.properties` 文件中添加以下配置: ``` spring.resources.static-locations=file:/path/to/files/ ``` - 后端提供一个接口,用于返回文件的URL。可以在控制器中编写如下代码: ```java @RestController public class FileController { @Value("${spring.resources.static-locations}") private String staticResourcePath; @GetMapping("/api/file/{fileName}") public ResponseEntity<Resource> getFile(@PathVariable String fileName) throws IOException { Path filePath = Paths.get(staticResourcePath + fileName); Resource resource = new UrlResource(filePath.toUri()); if (resource.exists() && resource.isReadable()) { return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + fileName + "\"") .body(resource); } else { // 文件不存在或无法读取 return ResponseEntity.notFound().build(); } } } ``` 2. 前端实现: - 在 Vue 组件中,使用 axios 或其他网络请求库发送 GET 请求,获取文件的 URL。例如: ```javascript import axios from 'axios'; // 在组件中调用接口获取文件 URL axios.get('/api/file/fileName.pdf') .then(response => { const fileUrl = response.data; // 使用文件预览插件或组件进行预览 // 例如,可以使用 pdf.js 进行 PDF 文件预览 // 或者使用 <img> 标签显示图片、使用 <video> 标签播放视频等 }) .catch(error => { console.error(error); }); ``` 需要注意的是,上述代码只是一种简单的实现方式,具体的预览方式和插件选择取决于你要预览的文件类型。你可以根据实际需求选择合适的插件或组件来实现文件预览功能,例如 pdf.js、viewer.js 等。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值