這個功能在項目開發中是很基礎的,平時用到的也很多,這里簡單記錄一下,以便以后使用的時候參考
前提業務要求:前台頁面展示數據,有下載按鈕,點擊下載,下載對應數據的二維碼。
首先,在pom.xml文件中添加依賴
<dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.3</version> <scope>compile</scope> </dependency> <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.3.3</version> <scope>compile</scope> </dependency>
其次,Controller的寫法(生成二維碼並以流的形式輸出到瀏覽器)
@RequestMapping("/test") public void dowanload(HttpServletRequest request,HttpServletResponse response) throws Exception { //二維碼中包含的信息 String content = "姓名:十二余\n博客:https://www.cnblogs.com/jing5464"; 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=" + "二維碼.png"); OutputStream outputStream = response.getOutputStream(); MatrixToImageWriter.writeToStream(bitMatrix, "png", outputStream); outputStream.flush(); outputStream.close(); }
最后,訪問地址:http://ip地址+端口號+訪問方法路徑
如:http://1.0.0.1:9090/test