import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
/**
* Created by dzk on 2021年8月26日
*/
public final class Utils {
/**
* 二维码下载
* 公用
*
* @param model Map类型的数据
* @param request 浏览器网络请求
* @param response 浏览器网络响应、输出
* @thorws 抛出异常主要是 writeException、IOException
* @Author dzk
* @Description 二维码下载
* @date 2021年8月26日
*/
public static void generatorErCode(Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) {
OutputStream outputStream = null;
try {
//二维码名称 model.get("erCodeName")
String name ="erCodeName";
//二维码中包含的信息 model.get("erContent")
String content = "erContent";
Map<EncodeHintType, Object> hints = new HashMap<>();
// 指定编码格式
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, 500, 500, hints);
//设置请求头
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(name + ".png", "UTF-8"));
response.setHeader("Content-Type", "application/octet-stream");
outputStream = response.getOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "png", outputStream);
} catch (Exception e) {
e.getMessage();
} finally {
if (outputStream != null) {
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.getMessage();
}
}
}
}
/**
* 显示文件大小
*
* @param size
* @return
*/
public static String getSmartSize(double size) {
String[] units = {"B", "KB", "MB", "GB", "TB", "PB"};
DecimalFormat df = new DecimalFormat("#.00");
for (int i = 0; i < units.length; i++) {
if (size < 1024) {
return df.format(size) + units[i];
}
size = size / 1024;
}
return String.format("%1$d", size, units[units.length - 1]);
}
}
在方法体内直接调用该发方法即可 【 Utils.generatorErCode(model, request, response);】
此文章是我开发过程的一个记录,方便我日后学习和复盘。若能帮到你不胜荣幸。