使用layui在前端接收后端的图片流来显示二维码,在前端使用iframe接收后端流来预览pdf

110 篇文章 2 订阅
14 篇文章 0 订阅

消息弹框的形式

因为我是在生成二维码之后,用zxing的工具类输出的流
所以这里介绍一下我用到的工具类的依赖

gradle

// https://mvnrepository.com/artifact/com.google.zxing/javase
compile group: 'com.google.zxing', name: 'javase', version: '3.2.1'

maven

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.2.1</version>
</dependency>

在这里插入图片描述
我这里的前端是coffee,如果是纯js的话改成js就行了

这里要注意一点,就是在请求后端的时候是以get请求方式请求的

coffee demo

html = "<img src='/api/qrcode/generateQRCode/#{shipmentId}'/>"
            layer.open(
                type: 1
                ,title : false
                ,closeBtn: false	//上面的demo的图片右上角有关闭X要去掉的话,加上这一行设置就行
                ,offset: 'auto'
                ,id: 'layerDemo'+ shipmentId
                ,content: html
                ,btn: '关闭'
                ,btnAlign: 'c'
                ,shade: 0
                ,yes: () ->
                    layer.closeAll();
            )

从官网捞了个js的demo

var html = "<img src='/api/qrcode/generateQRCode/#{shipmentId}'/>"
layer.open({
        type: 1
        ,offset: type //具体配置参考:http://www.layui.com/doc/modules/layer.html#offset
        ,id: 'layerDemo'+type //防止重复弹出
        ,content: html
        ,btn: '关闭全部'
        ,btnAlign: 'c' //按钮居中
        ,shade: 0 //不显示遮罩
        ,yes: function(){
          layer.closeAll();
        }
      });

前端大致就是上面这样,后端的话这里也给个demo,后端controller我用的springmvc
主要思路是把图片流写到response输出流中

controller
在这里插入图片描述

ResponseMessage generateQRCode(TtxSession sess,HttpServletResponse response,Long shipmentId){
        ServletOutputStream stream = null;
        try {
            ShipmentHeader sh = shSvc.getEntity(sess,shipmentId)
            String sql = """
                          select * 
                          from config_detail 
                          where warehouseCode = ? and recordType = 'invoiceValues' and identifier = 'qrCodePath'
                         """

            List<ConfigDetail> configDetails = template(sess).query(sql,new BeanPropertyRowMapper<ConfigDetail>(ConfigDetail.class),sh.warehouseCode)

            if(CollectionUtils.isEmpty(configDetails) || StringUtils.isEmpty(configDetails[0]?.value1)){
                return ResponseMessageFactory.error(sess,WaveMessages.MSG_WAVE_0147)
            }

            String selfDefine = configDetails[0].value2
            Map selfDefineMap = JSON.readValue(selfDefine,Map.class)
            Integer pictureSize = selfDefineMap.get("pictureSize") as Integer
            String picForm = selfDefineMap.get("pictureForm")
            String path = configDetails[0].value1

            String sepa = Matcher.quoteReplacement(File.separator)
            path = path.replaceAll("/",sepa)

            String filename = path + sh.code + "." + picForm
            BitMatrix bitMatrix = QRCodeUtil.createQRCode(sh.invoiceUrl,pictureSize,pictureSize)
            MatrixToImageWriter.writeToPath(bitMatrix,picForm,new File(filename).toPath())
			//输出到前端的图片肯定是要最新的不能有缓存,所以要设置no cache
			response.setHeader("Cache-Control","no-store");
            response.setHeader("Pragma","no-cache");
            response.setDateHeader("Expires",0);
            response.setContentType("image/jpg");	//设置格式,就是下面的picForm,我这里举了个jpg格式的例子
            stream = response.getOutputStream()
            //参数依次是:图片矩阵,图片格式picForm=jpg,ServletOutputStream stream = response.getOutputStream()
            MatrixToImageWriter.writeToStream(bitMatrix,picForm,stream)
            return ResponseMessageFactory.success(sess)
        } catch (Throwable t) {
            ExceptionManager.logException(sess,t)
            return ResponseMessageFactory.error(sess,t.getMessage())
        }finally{
            if (stream != null) {
                stream.flush();
                stream.close();
            }
        }

呃,上面的 bitMatrix 矩阵对象的来源在我生成二维码的博文那儿有

https://blog.csdn.net/weixin_43944305/article/details/106701133

在前端使用iframe接收后端流来预览pdf

layui的open中type=2的弹框其实是一个iframe
可以参考layui官方文档
https://www.layui.com/doc/modules/layer.html#type
在这里插入图片描述

<div id="getPdf">
    <button data-method="confirmTrans" class="layui-btn">预览pdf</button>
</div>

var $ = layui.jquery
        , layer = layui.layer;

$('#getPdf .layui-btn').on('click', function () {
    layer.open({
        type: 2
        , title: 'is test'
        , closeBtn: true
        , id: 1 //防止重复弹出
        , content: "/layui/getPdf"
        , shade: 0 //不显示遮罩
        , yes: function () {
            layer.closeAll();
        }
    });

});

后端返回流给前端

@GetMapping("getPdf")
public void getPdf(HttpServletResponse response){
    response.setContentType("application/pdf");
    FileInputStream in;
    OutputStream out;
    try {
        in = new FileInputStream(new File("C:\\Users\\xxx\\xxx.pdf"));
        out = response.getOutputStream();
        byte[] b = new byte[512];
        while ((in.read(b)) != -1) {
            out.write(b);
        }
        out.flush();
        in.close();
        out.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值