最近写项目用到了二维码,用于用户扫码临时登录,开始时是生成二维码,保存到项目中的文件夹,在提供一个下载功能,后来感觉这样有点麻烦,如果直接生成后发送到客户端的页面多好,后来做到了这样,下面是我的实现代码
public void erWeiMa() throws Exception {
HttpServletResponse response = ServletActionContext.getResponse();
HttpServletRequest quest = ServletActionContext.getRequest();
Domain domain = domainService.getIp();
String IP = domain.getIp();
// 设置页面不缓存
response.setHeader("Pragma", "No-cache");//指示请求或响应消息不能缓存,禁止浏览器缓存
response.setHeader("Cache-Control", "no-cache");//与上通常两者合用,Expires实体报头域给出响应过期的日期和时间
response.setDateHeader("Expires", 0);//设置非法的日期格式,如0
BufferedImage image = null;
ServletOutputStream stream = null;
// 二维码的图片格式
String format = "gif";
String content = "";//二维码内容
//设置二维码大小
int width2 = 200;
int height2 = 200;
Hashtable hints = new Hashtable();
// 内容所使用编码
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width2, height2,
hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.getHeight();
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF); // 二维码图片为黑白两色
}
}
} catch (Exception e) {
// TODO: handle exception
}
// 只有用这种解码方式才不出现乱码
String s = "attachment;filename=" + new String("".gif");//二维码的名字
response.addHeader("Content-Disposition", s);
/*Content-Disposition为属性名
disposition-type是以什么方式下载,如attachment为以附件方式下载
disposition-parm为默认保存时的文件名
服务端向客户端游览器发送文件时,使用attachment,这样浏览器会提示保存还是打开*/
OutputStream os = new BufferedOutputStream(response.getOutputStream());
response.setContentType("image/gif");
ImageIO.write(image, format, os);
os.flush();
os.close();
}
这是我的实现代码,每执行一次,就会向客户端页面以文件的形式发送,浏览器会识别它是个文件,自动弹出打开,还是下载的小弹出框,若我有什么地方写错了,或者理解有误,请发现的各位评论指正