栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

关于SpringBoot,Vue项目实现前端预览pdf文件流的解决方案

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

关于SpringBoot,Vue项目实现前端预览pdf文件流的解决方案

关于SpringBoot,Vue项目实现前端预览pdf文件流的解决方案 最近听到小伙伴遇到一个问题,要实现页面预览pdf功能,今天我就花点时间捣鼓了一下。当然解决方案有很多种,这里就介绍一下比较简单的实现方法。 1.首先我们先写后台接口,这里我们以输出流的形式来实现,这里一般数据库存储文件时以BLOB类型(也就是二进制字符串)来进行存储,这个可以Java可以用Object对象进行承接。Mybatis可以直接映射到实体类,用get方法来获取,话不多说,直接上代码。 controller层
    @RequestMapping("/queryPDF")
    public void showPDF(HttpServletRequest request, HttpServletResponse response) {
        InputStream inputStream = null;
        BufferedOutputStream bos = null;
        try {
            Map paramsMap = ParamsUtil.requestParamMap(request);
            List result = queryPdfService.showPDF(params);
            if (null != result && result.size() > 0) {
                //在这里设置头信息
                response.setContentType("application/pdf;charset=UTF-8");
                response.setHeader("Content-Disposition", "inline");
                OutputStream out = response.getOutputStream();
                BLOB blobs = (oracle.sql.BLOB) result.get(0);
                inputStream = blobs.getBinaryStream();
                // 需要引入pdfbox依赖
                PDDocument document = PDDocument.load(inputStream);
                document.setDocumentInformation(info);
                document.save(out); //输出
                document.close();
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
service层
	
    public List showPDF(Map map) throws Exception {
        List list = new ArrayList();
        try {
            PdfPojo pdfPojo = queryFileDao.queryPdfFile(map);
            // mybatis层可以直接映射到你的实体类
            Blob blobs = (Blob) pdfPojo.getFILEPDF();
            list.add(blobs);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
2.前端代码可以用Vue来实现,当然方法有很多,这里可以参考。
预览pdf
 queryPdf() {
      axios({
        methods: 'get',
        url: 'pdf/queryPDF',
        params: {
          //这里可以传参
          ID: this.preApproveCorpInfoForm.ID
        },
        responseType: 'blob',
        headers: {
          'Content-Type': 'application/json'
        }
      }).then(res => {
        console.log(res)
          let blob = new Blob([res.data], {type: 'application/pdf'})
          let href = URL.createObjectURL(blob)
          //这个是你接口的地址
          window.open('pdf/queryPDF?file='+encodeURIComponent(href));
      })
    },
今天的分享就到这里了,觉得有对你有帮助的话可以点赞加关注哦,我会不断分享一些开发的小技巧,如果小伙伴们有什么疑问的话,可以在评论区留言哦,我看到了会第一时间给出解答的爛。
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/969719.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号