Java生成二维码并浏览器下载,也可打包成zip下载
不说废话,直接上代码
1.单个生成二维码并下载
codeNo为前端传的需要生产二维码的内容
public void qrCode(HttpServletRequest request,HttpServletResponse response, String codeNo) throws Exception {
//二维码中包含的信息
String content = codeNo;
Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
// 指定编码格式
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
// 指定纠错级别(L--7%,M--15%,Q--25%,H--30%)
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
// 编码内容,编码类型(这里指定为二维码),生成图片宽度,生成图片高度,设置参数
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, 200, 200, hints);
//设置请求头
response.setHeader("Content-Type","application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + System.currentTimeMillis() + "二维码.png");
OutputStream outputStream = response.getOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "png", outputStream);
outputStream.flush();
outputStream.close();
}
2.多个二维码生产并打包成zip下载
codeNo为生成二维码的内容,name为二维码的名称,注意生成完是图片的形式,如果没有名称不好分辨哪个二维码是哪个生成的
public void qrCode(HttpServletRequest request,HttpServletResponse response, String codeNo, String name) throws Exception {
try {
String[] codeNoArr = codeNo.split(",");
String[] nameArr = name.split(",");
// 下载框代码
response.reset();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename="
+ URLEncoder.encode("二维码.zip", "UTF-8"));
OutputStream os = response.getOutputStream();
ZipOutputStream zos = new ZipOutputStream(os);
//每一个ZipEntry对应一个文件
ZipEntry ze = null;
for (int i = 0; i < codeNoArr.length; i++) {
//二维码内容放入这里
String content = codeNoArr[i];
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
Map hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = multiFormatWriter.encode(content,
BarcodeFormat.QR_CODE, 400, 400);
// 创建一个ZipEntry,并可以设置Name和其它的一些属性
ze = new ZipEntry(nameArr[i] + System.currentTimeMillis() + ".png");//name
//ze.setSize(sourceFile.length());
//ze.setTime(sourceFile.lastModified());
// 先将ZipEntry加到zos中,再写入实际的文件内容
zos.putNextEntry(ze);
MatrixToImageWriter.writeToStream(bitMatrix, "png", zos);//写入时写zos,而不是ze
}
zos.close();
os.flush();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
如果这篇文章有幸帮到了您,您有空的话可以点个关注或者推荐,谢谢了。