谷歌zxing 二维码后台生成,并在前端展示以及下载

一、展示效果

1|数据表格row按钮

在这里插入图片描述

2|点击查看二维码:跳转新窗口,也可以做弹窗,新窗口是为了方便直接通过浏览器打印

在这里插入图片描述

3|点击下载:保存到浏览器下载路径

在这里插入图片描述
在这里插入图片描述

二、后台代码

1. pom引入依赖

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

2. 二维码生成工具类

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

public class QRCodeGenerator {

    private static final int WIDTH = 350;

    private static final int HEIGHT = 350;

    // 二维码保存为图片
    public static void generateQRCodeImage(String text, String filePath) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, QRCodeGenerator.WIDTH, QRCodeGenerator.HEIGHT);
        mkdirs(filePath);
        Path path = FileSystems.getDefault().getPath(filePath);
        MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
    }

    // 二维码保存为字节数组
    public static byte[] getQRCodeImage(String text) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, WIDTH, HEIGHT);

        ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
        pngOutputStream.flush();
        pngOutputStream.close();
        return pngOutputStream.toByteArray();
    }

    public static ByteArrayOutputStream getQRCodeOutputStream(String text) throws WriterException, IOException {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, WIDTH, HEIGHT);

        ByteArrayOutputStream pngOutputStream = new ByteArrayOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "PNG", pngOutputStream);
        pngOutputStream.flush();
        pngOutputStream.close();
        return pngOutputStream;
    }

    private static void mkdirs(String destPath){
        File file = new File(destPath);
        if(!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }

}

3. 服务层

 @Override
    public byte[] getQRCode(ComponentBox componentBox) throws IOException, WriterException {
        final String sns = componentBox.getSns();
        final String boxNo = componentBox.getBoxNo();
        final String qrcodeStr = boxNo
                + "["
                + sns
                + "]";
        return QRCodeGenerator.getQRCodeImage(qrcodeStr);
    }

三、前端

1. 新建二维码展示页面,并在router/index.js 配置路由

	二维码以base64格式展示在跳转的页面:qrcode.vue
<template>
  <div style="width: 600px; margin: 0 auto; margin-top: 100px">
    <div>
      <el-image :src="base64ImgData">
        <div slot="placeholder" class="image-slot">
          加载中<span class="dot">...</span>
        </div>
      </el-image>
    </div>
    <div style="margin-top: 25px;"
        v-if="snList.length > 0"  >
      <h2 style="color:#e50c0c; font-weight: bold; font-size: 35px">{{boxNo}}</h2>
      <span style="
            color: green;
            font-weight: bold;
            font-size: 25px;"
          v-for="(value, key, index) in snList">
        {{value}}</span>
    </div>
  </div>
</template>
<script>
export default {
    data() {
      return{
        base64ImgData: null,
        boxNo: null,
        snList:[]
      }
    },
    created() {
      if (this.isSuperAdmin) {
        // 获取列表数据
        this.getParams();
      } else {
        if (this.permMenuArr.indexOf('componentBoxList') > -1) {
          // 获取列表数据
          this.getParams();
        }
      }
    },
    methods: {
      getParams(){
        let imgData, sns;
        if(localStorage.getItem("imgData")){
          imgData = localStorage.getItem("imgData")
          this.base64ImgData = 'data:image/png;base64,' + imgData
        }
        if(localStorage.getItem("sns")){
          sns = localStorage.getItem("sns")
          this.snList = sns.split(",");
        }
        if(localStorage.getItem("boxNo")){
          this.boxNo = localStorage.getItem("boxNo")
        }
      }
    }
}
</script>
<style>
body{
  text-align: center;
}
</style>

2. 点击按钮对应的JS代码

 // 获取二维码,跳转新窗口qrcode.vue 并传参(参数不显示在浏览器地址栏)
    QRCode(row) {
      let data = {boxNo: row.boxNo, sns: row.sns}
      getRQCode(data).then(res => {
        let imgData = res.data.data
        let href = this.$router.resolve({
          path:'/component/componentRadarBox/qrcode'
        })
        localStorage.setItem("sns", row.sns)
        localStorage.setItem("boxNo", row.boxNo)
        localStorage.setItem("imgData", imgData)
        window.open(href.href, '_blank'); // 跳转新建的二维码展示页面
      })
    },
    // 下载二维码
    downloadQRCode: function (row) {
      let query = {boxNo: row.boxNo, sns: row.sns}
      getRQCode(query).then(res => {
        let imgData = 'data:image/png;base64,' + res.data.data
        let datetime = this.getDatetime();
        this.downloadFile(row.boxNo+ '-' + datetime + '.png', imgData)
      })
    },
    downloadFile(fileName, content) {
      let aLink = document.createElement('a');
      let blob = this.base64ToBlob(content); //new Blob([content]);

      let evt = document.createEvent("HTMLEvents");
      evt.initEvent("click", true, true);//initEvent 不加后两个参数在FF下会报错  事件类型,是否冒泡,是否阻止浏览器的默认行为
      aLink.download = fileName;
      aLink.href = URL.createObjectURL(blob);
      // aLink.dispatchEvent(evt);
      aLink.click()
    },
    base64ToBlob(code) {
      let parts = code.split(';base64,');
      let contentType = parts[0].split(':')[1];
      let raw = window.atob(parts[1]);
      let rawLength = raw.length;
      let uInt8Array = new Uint8Array(rawLength);
      for (let i = 0; i < rawLength; ++i) {
        uInt8Array[i] = raw.charCodeAt(i);
      }
      return new Blob([uInt8Array], {type: contentType});
    },
    // 获取日期字符串(yyyy-MM-dd-HH-mm-ss)
    getDatetime() {
      let d = new Date();
      let year = d.getFullYear();
      let month = change(d.getMonth() + 1);
      let day = change(d.getDate());
      let hour = change(d.getHours());
      let minute = change(d.getMinutes());
      let second = change(d.getSeconds());
      function change(t) {
        if (t < 10) {
          return "0" + t;
        } else {
          return t;
        }
      }
      let time = year + '-' + month + '-' + day + '-'
        + hour + '-' + minute + '-' + second;
      return time;
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值