1.生成二维码方法
@RequiresPermissions("cfm:wCorporateinformationmanagement:edit")
@RequestMapping(value = "produce")
@ResponseBody
public Map<String, String> produce(String id,Model model,HttpServletRequest request) throws Exception{
WCorporateinformationmanagement cfm =wCorporateinformationmanagementService.findByid(id);
String cpn = cfm.getCompanyname();
String dpg =cfm.getDutyparagraph();
name = id;
MultiFormatWriter writer = new MultiFormatWriter();
InetAddress address =InetAddress.getLocalHost();
String localIp = address.getHostAddress();
System.out.println("http://"+localIp+":"+request.getLocalPort() + request.getContextPath());
String ip = "http://"+localIp+":"+request.getLocalPort()+ request.getContextPath()+"/f"+"/user/wUser/login"+"?companyname="+cpn+"&dutyparagraph="+dpg;
String contents = id;
int w = 200;
int h = 200;
HashMap<EncodeHintType, Object> Hints = new HashMap<EncodeHintType, Object>();
Hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//二进制矩阵数据
BitMatrix bitMatrix = writer.encode(contents, BarcodeFormat.QR_CODE, w, h,Hints);
//本身提提供的类
//MatrixToImageWriter.writeToPath(bitMatrix, "png", new File("F:/1.png").toPath());
BufferedImage qr = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
for(int x=0;x<w;x++) {
for(int y = 0;y<h;y++) {
if(bitMatrix.get(x, y)) {
qr.setRGB(x, y, 0x000000);
}else {
qr.setRGB(x, y, 0xFFFFFF);
}
}
}
String url = request.getSession().
getServletContext().getRealPath("/")+"uploadFile\\"+new Date().getTime()+".png";
File file = new File(url);
if(!file.exists()){
file.mkdirs();
}
String top = request.getContextPath();
String top1 = top.substring(1,top.length());
String top2 = "";
top2 ="\\" + top1.substring(0,top1.length());
ImageIO.write(qr, "png", new File(url));
String newurl = url.substring(url.indexOf(top2),url.length());
Map<String, String> map = new HashMap<String, String>();
map.put("image", newurl);
map.put("url", url);
return map;
}
1.1
动态的显示url,和把需要的参数保存到二维码。
1.2
用url保存二维码的路径
1.3
这是生成二维码的方法。
2.1前台用js接受 生成二维码 按键
2.2用Ajax写好要传的参数和路径
3.1 接收生成二维码方法返回的值。
用键值对分别把显示图片路径和下载路径传到前台
data就表示接收到的map。
3.2用jbox弹框显示图片
然后把用a标签跳转到download方法上并把下载图片需要的动态名字和下载路径两个参数带过去
4.1 download方法
@RequestMapping(value = "/download")
public String download(@RequestParam String name,@RequestParam String url, HttpServletResponse response, HttpServletRequest request) throws Exception{
System.out.println("==========================");
System.out.println("开始下载");
InputStream in = null ;
OutputStream out = null ;
try
{
in = new FileInputStream(url); //获取文件的流
int len = 0;
byte buf[] = new byte[1024];//缓存作用
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(name + ".png", "UTF-8"));
out = response.getOutputStream();//输出流
while( (len = in.read(buf)) > 0 ) //切忌这后面不能加 分号 ”;“
{
out.write(buf, 0, len);//向客户端输出,实际是把数据存放在response中,然后web服务器再去response中读取
}
in.close();
out.close();
}finally{
//TODO
}
return null;
}
注:把两个参数传值而不用全局变量是为了避免两个电脑同时点的时候发生冲突。