需求
扫描二维码跳转员工录入界面进行添加员工信息
- 批量下载二维码:选择多个企业进行打包下载
- 查看二维码:在线预览
代码
引入组件
import QRCode from 'qrcodejs2'
一、批量下载二维码
1. 前端
// 批量下载二维码
hanleBatchDown () {
let fileName = '二维码'
this.axios({
method: 'get',
url: 'http://localhost:8080/qrcode/zip',
params: '',
responseType: 'blob'
}).then(data => {
if (data) {
let url = window.URL.createObjectURL(data)
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', fileName + '.zip')
document.body.appendChild(link)
link.click()
document.body.removeChild(link) // 下载完成移除元素
window.URL.revokeObjectURL(url) // 释放掉blob对象
this.$message.success('批量下载成功!')
} else {
this.$message.error('下载失败' + data.message)
}
this.loading = false
})
}
2. 后端
@GetMapping("/qrcode/zip")
public void downloadZip(HttpServletRequest request, HttpServletResponse response) throws IOException {
List<BCompany> bCompanyList = bCompanyService.list();
if (bCompanyList != null) {
OutputStream outputStream = response.getOutputStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
for (int i = 0; i < bCompanyList.size(); i++) {
String url = "http://localhost:8080/test.html" + "?" + "companyName=" + URLEncoder.encode(bCompanyList.get(i).getCompanyName(), "utf-8") + "&companyId=" + bCompanyList.get(i).getId();
BufferedImage buffImg = QRcodeUntil.getBufferedImage(null, url);
ZipEntry entry = new ZipEntry(bCompanyList.get(i).getCompanyName() + ".png");
zipOutputStream.putNextEntry(entry);
ImageIO.write(buffImg, "png", zipOutputStream);
}
zipOutputStream.flush();
zipOutputStream.close();
outputStream.flush();
outputStream.close();
}
}
二、预览二维码
1. 前端 antd-vue
<a @click="scewm(record.companyName,record.id)">预览二维码</a>
<a-modal :centered="true"
:maskClosable="false"
:width="460"
@cancel="handleCancel"
destroyOnClose
title="查看二维码"
v-model="show">
<a-row :gutter="24"
id="printContainer">
<div id="qrcode" ref="qrcode"></div>
</a-row>
<template slot="footer">
<a-button @click="hanleDown(companyName,companyId)"
type="primary">下载
</a-button>
<a-button @click="handleCancel"
key="back">关闭
</a-button>
</template>
</a-modal>
2. JS
computed: {
show: {
get: function () {
return true
},
set: function () {
}
}
},
//@TODO 监听visible变化
watch: {
// 生成二维码js必须在 this.$nextTick(function(){调用})或setTimeout(() => { 调用 }, 100),是为了确保二维码容器DOM已经存在
visible(newVisible) {
if (newVisible) {
this.$nextTick(function () {
this.init(this.companyName, this.companyId)
})
}
}
}
methods: {
//@TODO 前端展示二维码
scewm(companyName, id) {
//显示二维码
this.visible = true
this.newVisible = true
this.companyName = companyName
this.companyId = id
},
init(companyName, id) {
// 为了防止重复生成二维码,使用置空进行控制
document.getElementById('qrcode').innerHTML = ''
// 设置二维码内容 显示内容(text所指向内容)必须是UTF-8编码格式。
const content = companyName + "@" + id
this.qrcode = new QRCode('qrcode', {
width: 260,
height: 260,
colorDark: '#000',
colorLight: '#fff',
correctLevel: QRCode.CorrectLevel.L, // 容错率,L/M/H
text: content
});
}
}