在页面设置一个“生成二维码”按钮,点击按钮,调用后台生成一个二维码图片,直接在浏览器下载下来。
生成二维码工具类QRCodeUtil.java:这个工具类需要导入依赖
com.google.zxing
core
3.1.0
package com.dosion.core.common.utils;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.common.BitMatrix;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class QRCode {
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
//生成二维码
public static String createQrCode(String url, String path, String fileName) {
try {
Map hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE, 400, 400, hints);
File file = new File(path, fileName);
if (file.exists() || ((file.getParentFile().exists() || file.getParentFile().mkdirs()) && file.createNewFile())) {
writeToFile(bitMatrix, "jpg", file);
System.out.println("搞定:" + file);
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//下载二维码
public static void downFile(String url, String fileName, HttpServletRequest request, HttpServletResponse response) {
try {
//1.定义ContentType为("multipart/form-data")让浏览器自己解析文件格式
response.setContentType("multipart/form-data");
//2.中文名转码
//response.setHeader("Content-disposition", "attachment; filename=\""+encodeChineseDownloadFileName(request, fileName+".xlsx") +"\"");
response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
//获得文件
File file = new File(url+fileName);
FileInputStream in = new FileInputStream(file);
//3.将文件写入缓冲区OutputStream(out)
OutputStream out = new BufferedOutputStream(response.getOutputStream());
int b = 0;
byte[] buffer = new byte[2048];
while ((b=in.read(buffer)) != -1){
//4.将缓冲区文件输出到客户端(out)
out.write(buffer,0,b);
}
in.close();
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//生成带图二维码
public static void MatrixToImage(BitMatrix matrix,String format,String path, String fileName) throws IOException{
File f = new File(path, fileName);
//将我们的logo提取出来,建议这里单独写一个方法,我只是为了方便
BufferedImage b = ImageIO.read(new File("e:/1.jpg"));
//将logo弄成70*70,如果想大点,记得要提高我们二维码的容错率
Image image = b.getScaledInstance(70, 70,Image.SCALE_FAST);
BufferedImage bi = toBufferedImage(matrix);
//获取二维码画刷
Graphics g=bi.getGraphics();
//定位
g.drawImage(image ,165,165, null);
//二维码画到相应文件位置,结束。
if(ImageIO.write(bi, format, f)){
}
System.out.println("二维码生成成功!");
}
private static BufferedImage toBufferedImage(BitMatrix matrix){
BufferedImage bi=new BufferedImage(matrix.getWidth(), matrix.getHeight(), BufferedImage.TYPE_INT_RGB);
for(int i=0;i
下载二维码工具类DownLoadUtil.java:
package com.dosion.core.common.utils.excel;
import com.dosion.core.common.utils.StringUtils;
import org.springframework.core.io.DefaultResourceLoader;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
/**
* 导出工具类
* @author ty
* @version 2019-2-13
*/
public class DownLoadUtil {
/**
*
* @Title: encodeChineseDownloadFileName
*
* @param @param request
* @param @param pFileName
* @param @return
* @param @throws UnsupportedEncodingException
* @return String
* @throws
*/
public static String encodeChineseDownloadFileName(HttpServletRequest request, String pFileName)
throws UnsupportedEncodingException {
String filename = null;
String agent = request.getHeader("USER-AGENT");
if (null != agent) {
if (-1 != agent.indexOf("Firefox")) {
//Firefox
filename = "=?UTF-8?B?" + (new String(org.apache.commons.codec.binary.Base64.encodeBase64(pFileName.getBytes("UTF-8")))) + "?=";
} else if (-1 != agent.indexOf("Chrome")) {
//Chrome
filename = new String(pFileName.getBytes(), "ISO8859-1");
} else {
//IE7+
filename = java.net.URLEncoder.encode(pFileName, "UTF-8");
//替换特殊字符
filename = StringUtils.replace(filename, "+", "%20");
}
} else {
filename = pFileName;
}
return filename;
}
public static String getPysicalPath(String virtualPath,HttpServletRequest request) {
//获得根绝对路径
String physicalPath = getProjectPath();
//获得项目路径
String basePath = request.getContextPath();
if(virtualPath.startsWith(basePath)){
virtualPath = virtualPath.substring(basePath.length());
}
return physicalPath + virtualPath;
}
/**
* @Title: downFile
* @Description:
* @param @param url文件url
* @param @param fileName 文件名
* @param @param response
* @return void
* @throws
*/
public static void downFile(String url,String fileName,HttpServletRequest request,HttpServletResponse response) {
try {
//1.定义ContentType为("multipart/form-data")让浏览器自己解析文件格式
response.setContentType("multipart/form-data");
//2.中文名转码
//response.setHeader("Content-disposition", "attachment; filename=\""+encodeChineseDownloadFileName(request, fileName+".xlsx") +"\"");
response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1") + ".xlsx");
//获得文件
File file = new File(url);
FileInputStream in = new FileInputStream(file);
//3.将文件写入缓冲区OutputStream(out)
OutputStream out = new BufferedOutputStream(response.getOutputStream());
int b = 0;
byte[] buffer = new byte[2048];
while ((b=in.read(buffer)) != -1){
//4.将缓冲区文件输出到客户端(out)
out.write(buffer,0,b);
}
in.close();
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 获取工程项目根路径
* @return
*/
public static String getProjectPath(){
// 如果配置了工程路径,则直接返回,否则自动获取。
String projectPath = null;
// if (StringUtils.isNotBlank(projectPath)){
// return projectPath;
// }
try {
File file = new DefaultResourceLoader().getResource("").getFile();
if (file != null){
while(true){
File f = new File(file.getPath() + File.separator + "src" + File.separator + "main");
if (f == null || f.exists()){
break;
}
if (file.getParentFile() != null){
file = file.getParentFile();
}else{
break;
}
}
projectPath = file.toString();
}
} catch (IOException e) {
e.printStackTrace();
}
return projectPath;
}
}
前台代码:
//生成二维码
GenerateQRcode:function(classId){
var url = api.user.generateClassQRCode;
fetch(url,{
method: 'POST',
/*headers: new Headers({
'token':dataUtils.getData(config.key.tokenKey) // 指定提交方式为表单提交
}),*/
}).then(res => res.blob().then(blob => {
var a = document.createElement('a');
var url = window.URL.createObjectURL(blob);
var filename = 'rqcode.jpg';
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
}));
},
后台代码:
@ApiOperation("生成班级二维码")
@RequestMapping(value = "generateClassQRCode", method = RequestMethod.POST)
public void generateClassQRCode(String classId,HttpServletRequest request,HttpServletResponse response){
//生成二维码
//要生成二维码的网址
String url = "https://www.baidu.com/";
//指定生成路径
String uploadPath = "/src/main/resources/temp/";
String fileName = "QRcode";
//将虚拟路径转为物理路径
String path = DownLoadUtil.getPysicalPath(uploadPath + fileName+"/", request);
//生成二维码
QRCode.createQrCode(url,path,fileName+".jpg");
//下载二维码
QRCode.downFile(path,fileName+".jpg",request,response);
}
后台二维码图片地址:
把成果贴这里: