关键词搜索

源码搜索 ×
×

Java 快速实现二维码图片项目路径生成和文件压缩下载

发布2019-10-21浏览1130次

详情内容

Java 快速实现二维码图片项目路径生成和文件压缩下载。Zxing工具类在这个小demo中基本用不到,需要做复杂的二维码还是可以的,如二维码嵌入Logo图片等。

目录

Zxing二维码生成工具

服务器快速二维码图片管理

二维码图片生成工具

图片压缩下载工具

二维码控制器

测试效果

生成二维码

下载ZIP压缩文件


Zxing二维码生成工具

pom.xml

  1. <!-- Google二维码 -->
  2. <dependency>
  3. <groupId>com.google.zxing</groupId>
  4. <artifactId>core</artifactId>
  5. <version>3.3.3</version>
  6. </dependency>
  7. <dependency>
  8. <groupId>com.google.zxing</groupId>
  9. <artifactId>javase</artifactId>
  10. <version>3.3.3</version>
  11. </dependency>

QRCodeUtil.java

  1. package com.boonya.util;
  2. import java.awt.Color;
  3. import java.awt.Graphics2D;
  4. import java.awt.Image;
  5. import java.awt.image.BufferedImage;
  6. import java.io.File;
  7. import java.io.IOException;
  8. import java.util.Hashtable;
  9. import javax.imageio.ImageIO;
  10. import com.google.zxing.BarcodeFormat;
  11. import com.google.zxing.EncodeHintType;
  12. import com.google.zxing.MultiFormatWriter;
  13. import com.google.zxing.client.j2se.MatrixToImageConfig;
  14. import com.google.zxing.client.j2se.MatrixToImageWriter;
  15. import com.google.zxing.common.BitMatrix;
  16. import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
  17. /**
  18. *
  19. * @function 功能:二维码生成工具
  20. * @author PJL
  21. * @package com.forestar.util
  22. * @filename QRCodeUtil.java
  23. * @time 2019 2019年9月25日 上午11:32:55
  24. */
  25. public class QRCodeUtil {
  26. private static int width = 300; // 二维码宽度
  27. private static int height = 300; // 二维码高度
  28. private static int onColor = 0xFF000000; // 前景色
  29. private static int offColor = 0xFFFFFFFF; // 背景色
  30. private static int margin = 1; // 白边大小,取值范围0~4
  31. private static ErrorCorrectionLevel level = ErrorCorrectionLevel.L; // 二维码容错率
  32. /**
  33. * 生成二维码
  34. *
  35. * @param params
  36. * QRCodeParams属性:txt、fileName、filePath不得为空;
  37. * @throws Exception
  38. */
  39. public static void generateQRImage(QRCodeParams params)
  40. throws Exception {
  41. if (params == null || params.getFileName() == null
  42. || params.getFilePath() == null || params.getTxt() == null) {
  43. throw new Exception("二维码参数错误");
  44. }
  45. try {
  46. initData(params);
  47. String imgPath = params.getFilePath();
  48. String imgName = params.getFileName();
  49. String txt = params.getTxt();
  50. if (params.getLogoPath() != null
  51. && !"".equals(params.getLogoPath().trim())) {
  52. generateQRImage(txt, params.getLogoPath(), imgPath, imgName,
  53. params.getSuffixName());
  54. } else {
  55. generateQRImage(txt, imgPath, imgName, params.getSuffixName());
  56. }
  57. } catch (Exception e) {
  58. e.printStackTrace();
  59. }
  60. }
  61. /**
  62. * 生成二维码
  63. *
  64. * @param txt
  65. * //二维码内容
  66. * @param imgPath
  67. * //二维码保存物理路径
  68. * @param imgName
  69. * //二维码文件名称
  70. * @param suffix
  71. * //图片后缀名
  72. */
  73. public static void generateQRImage(String txt, String imgPath,
  74. String imgName, String suffix) {
  75. File filePath = new File(imgPath);
  76. if (!filePath.exists()) {
  77. filePath.mkdirs();
  78. }
  79. File imageFile = new File(imgPath, imgName);
  80. Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
  81. // 指定纠错等级
  82. hints.put(EncodeHintType.ERROR_CORRECTION, level);
  83. // 指定编码格式
  84. hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
  85. hints.put(EncodeHintType.MARGIN, margin); // 设置白边
  86. try {
  87. MatrixToImageConfig config = new MatrixToImageConfig(onColor,
  88. offColor);
  89. BitMatrix bitMatrix = new MultiFormatWriter().encode(txt,
  90. BarcodeFormat.QR_CODE, width, height, hints);
  91. // bitMatrix = deleteWhite(bitMatrix);
  92. MatrixToImageWriter.writeToPath(bitMatrix, suffix,
  93. imageFile.toPath(), config);
  94. } catch (Exception e) {
  95. e.printStackTrace();
  96. }
  97. }
  98. /**
  99. * 生成带logo的二维码图片
  100. *
  101. * @param txt
  102. * //二维码内容
  103. * @param logoPath
  104. * //logo绝对物理路径
  105. * @param imgPath
  106. * //二维码保存绝对物理路径
  107. * @param imgName
  108. * //二维码文件名称
  109. * @param suffix
  110. * //图片后缀名
  111. * @throws Exception
  112. */
  113. public static void generateQRImage(String txt, String logoPath,
  114. String imgPath, String imgName, String suffix) throws Exception {
  115. File filePath = new File(imgPath);
  116. if (!filePath.exists()) {
  117. filePath.mkdirs();
  118. }
  119. if (imgPath.endsWith("/")) {
  120. imgPath += imgName;
  121. } else {
  122. imgPath += "/" + imgName;
  123. }
  124. Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
  125. hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
  126. hints.put(EncodeHintType.ERROR_CORRECTION, level);
  127. hints.put(EncodeHintType.MARGIN, margin); // 设置白边
  128. BitMatrix bitMatrix = new MultiFormatWriter().encode(txt,
  129. BarcodeFormat.QR_CODE, width, height, hints);
  130. File qrcodeFile = new File(imgPath);
  131. writeToFile(bitMatrix, suffix, qrcodeFile, logoPath);
  132. }
  133. /**
  134. *
  135. * @param matrix
  136. * 二维码矩阵相关
  137. * @param format
  138. * 二维码图片格式
  139. * @param file
  140. * 二维码图片文件
  141. * @param logoPath
  142. * logo路径
  143. * @throws IOException
  144. */
  145. public static void writeToFile(BitMatrix matrix, String format, File file,
  146. String logoPath) throws IOException {
  147. BufferedImage image = toBufferedImage(matrix);
  148. Graphics2D gs = image.createGraphics();
  149. int ratioWidth = image.getWidth() * 2 / 10;
  150. int ratioHeight = image.getHeight() * 2 / 10;
  151. // 载入logo
  152. Image img = ImageIO.read(new File(logoPath));
  153. int logoWidth = img.getWidth(null) > ratioWidth ? ratioWidth : img
  154. .getWidth(null);
  155. int logoHeight = img.getHeight(null) > ratioHeight ? ratioHeight : img
  156. .getHeight(null);
  157. int x = (image.getWidth() - logoWidth) / 2;
  158. int y = (image.getHeight() - logoHeight) / 2;
  159. gs.drawImage(img, x, y, logoWidth, logoHeight, null);
  160. gs.setColor(Color.black);
  161. gs.setBackground(Color.WHITE);
  162. gs.dispose();
  163. img.flush();
  164. if (!ImageIO.write(image, format, file)) {
  165. throw new IOException("Could not write an image of format "
  166. + format + " to " + file);
  167. }
  168. }
  169. public static BufferedImage toBufferedImage(BitMatrix matrix) {
  170. int width = matrix.getWidth();
  171. int height = matrix.getHeight();
  172. BufferedImage image = new BufferedImage(width, height,
  173. BufferedImage.TYPE_INT_RGB);
  174. for (int x = 0; x < width; x++) {
  175. for (int y = 0; y < height; y++) {
  176. image.setRGB(x, y, matrix.get(x, y) ? onColor : offColor);
  177. }
  178. }
  179. return image;
  180. }
  181. public static BitMatrix deleteWhite(BitMatrix matrix) {
  182. int[] rec = matrix.getEnclosingRectangle();
  183. int resWidth = rec[2] + 1;
  184. int resHeight = rec[3] + 1;
  185. BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
  186. resMatrix.clear();
  187. for (int i = 0; i < resWidth; i++) {
  188. for (int j = 0; j < resHeight; j++) {
  189. if (matrix.get(i + rec[0], j + rec[1]))
  190. resMatrix.set(i, j);
  191. }
  192. }
  193. return resMatrix;
  194. }
  195. private static void initData(QRCodeParams params) {
  196. if (params.getWidth() != null) {
  197. width = params.getWidth();
  198. }
  199. if (params.getHeight() != null) {
  200. height = params.getHeight();
  201. }
  202. if (params.getOnColor() != null) {
  203. onColor = params.getOnColor();
  204. }
  205. if (params.getOffColor() != null) {
  206. offColor = params.getOffColor();
  207. }
  208. if (params.getLevel() != null) {
  209. level = params.getLevel();
  210. }
  211. }
  212. }

QRCodeParams.java

  1. package com.boonya.util;
  2. import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
  3. /**
  4. *
  5. * @function 功能:二维码设置参数
  6. * @author PJL
  7. * @package com.forestar.util
  8. * @filename QRCodeParams.java
  9. * @time 2019 2019年9月25日 上午11:00:17
  10. */
  11. public class QRCodeParams {
  12. private String txt; // 二维码内容
  13. private String qrCodeUrl; // 二维码网络路径
  14. private String filePath; // 二维码生成物理路径
  15. private String fileName; // 二维码生成图片名称(包含后缀名)
  16. private String logoPath; // logo图片
  17. private Integer width = 300; // 二维码宽度
  18. private Integer height = 300; // 二维码高度
  19. private Integer onColor = 0xFF000000; // 前景色
  20. private Integer offColor = 0xFFFFFFFF; // 背景色
  21. private Integer margin = 1; // 白边大小,取值范围0~4
  22. private ErrorCorrectionLevel level = ErrorCorrectionLevel.L; // 二维码容错率
  23. public String getTxt() {
  24. return txt;
  25. }
  26. public void setTxt(String txt) {
  27. this.txt = txt;
  28. }
  29. public String getFilePath() {
  30. return filePath;
  31. }
  32. public void setFilePath(String filePath) {
  33. this.filePath = filePath;
  34. }
  35. public String getFileName() {
  36. return fileName;
  37. }
  38. public void setFileName(String fileName) {
  39. this.fileName = fileName;
  40. }
  41. public Integer getWidth() {
  42. return width;
  43. }
  44. public void setWidth(Integer width) {
  45. this.width = width;
  46. }
  47. public Integer getHeight() {
  48. return height;
  49. }
  50. public void setHeight(Integer height) {
  51. this.height = height;
  52. }
  53. public String getQrCodeUrl() {
  54. return qrCodeUrl;
  55. }
  56. public void setQrCodeUrl(String qrCodeUrl) {
  57. this.qrCodeUrl = qrCodeUrl;
  58. }
  59. public String getLogoPath() {
  60. return logoPath;
  61. }
  62. public void setLogoPath(String logoPath) {
  63. this.logoPath = logoPath;
  64. }
  65. public Integer getOnColor() {
  66. return onColor;
  67. }
  68. public void setOnColor(Integer onColor) {
  69. this.onColor = onColor;
  70. }
  71. public Integer getOffColor() {
  72. return offColor;
  73. }
  74. public void setOffColor(Integer offColor) {
  75. this.offColor = offColor;
  76. }
  77. public ErrorCorrectionLevel getLevel() {
  78. return level;
  79. }
  80. public void setLevel(ErrorCorrectionLevel level) {
  81. this.level = level;
  82. }
  83. /**
  84. * 返回文件后缀名
  85. *
  86. * @return
  87. */
  88. public String getSuffixName() {
  89. String imgName = this.getFileName();
  90. if (imgName != null && !"".equals(imgName)) {
  91. String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
  92. return suffix;
  93. }
  94. return "";
  95. }
  96. public Integer getMargin() {
  97. return margin;
  98. }
  99. public void setMargin(Integer margin) {
  100. this.margin = margin;
  101. }
  102. }

服务器快速二维码图片管理

二维码图片生成工具

通过操作输出文件流实现:FileGenerateUtils.java

  1. package com.boonya.util;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.OutputStream;
  6. import java.net.URISyntaxException;
  7. import java.util.HashMap;
  8. import java.util.Map;
  9. import javax.servlet.http.HttpServletResponse;
  10. import com.boonya.core.util.StringUtils;
  11. import com.google.zxing.BarcodeFormat;
  12. import com.google.zxing.EncodeHintType;
  13. import com.google.zxing.MultiFormatWriter;
  14. import com.google.zxing.WriterException;
  15. import com.google.zxing.client.j2se.MatrixToImageWriter;
  16. import com.google.zxing.common.BitMatrix;
  17. import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
  18. /**
  19. * @function 功能:二维码文件生成到指定路径
  20. * @author PJL
  21. * @package com.boonya.util
  22. * @filename FileGenerateUtils.java
  23. * @time 2019 2019年10月21日 下午1:07:52
  24. */
  25. public class FileGenerateUtils {
  26. private static String FILE_SERVER_ADDRESS="";
  27. static{
  28. try {
  29. FILE_SERVER_ADDRESS = FileGenerateUtils.class.getResource("").toURI().getPath();
  30. } catch (URISyntaxException e) {
  31. e.printStackTrace();
  32. }
  33. FILE_SERVER_ADDRESS = FILE_SERVER_ADDRESS.substring(0,FILE_SERVER_ADDRESS.lastIndexOf("/WEB-INF/") + 1);
  34. if(!FILE_SERVER_ADDRESS.endsWith("/")){
  35. FILE_SERVER_ADDRESS+="/";
  36. }
  37. }
  38. /**
  39. * 获取文件基础路径
  40. *
  41. * @return
  42. */
  43. public static String getBasePath(){
  44. return FILE_SERVER_ADDRESS;
  45. }
  46. /**
  47. * 获取相对路径
  48. * @param qrcode
  49. * @return
  50. */
  51. public static String getRelativePath(String qrcode){
  52. String sheng=qrcode.substring(0,2);
  53. String shi=qrcode.substring(0,4);
  54. String xian=qrcode.substring(0,6);
  55. return "/qrcode/"+sheng+"/"+shi+"/"+xian+"/"+qrcode+".png";
  56. }
  57. /**
  58. * 获取固定规则的文件路径
  59. * @param qrcode
  60. * @return
  61. */
  62. public static String getFilePath(String qrcode){
  63. String sheng=qrcode.substring(0,2);
  64. String shi=qrcode.substring(0,4);
  65. String xian=qrcode.substring(0,6);
  66. File xianPath=new File(FILE_SERVER_ADDRESS+"qrcode/"+sheng+"/"+shi+"/"+xian);
  67. if(!xianPath.exists()){
  68. xianPath.mkdirs();
  69. }
  70. String filePath=xianPath.getPath()+"/"+qrcode+".png";
  71. return filePath;
  72. }
  73. /**
  74. * 创建二维码路径和文件
  75. *
  76. * @param qrcode
  77. * @throws Exception
  78. */
  79. public static String mkdirAndFile(String qrcode) throws Exception{
  80. String filePath=getFilePath(qrcode);
  81. File path=new File(filePath);
  82. if(!path.exists()){
  83. path.createNewFile();
  84. }
  85. return filePath;
  86. }
  87. /**
  88. * 根据二维码编号写入文件流到指定路径
  89. * @param qrcode
  90. * @return
  91. * @throws Exception
  92. */
  93. public static boolean generateQRCodeImage(String qrcode) throws Exception{
  94. if(StringUtils.isEmpty(qrcode)){
  95. return false;
  96. }
  97. String filePath=mkdirAndFile(qrcode);
  98. FileOutputStream outputStream=new FileOutputStream(filePath);
  99. generateStreamFile(qrcode, outputStream);
  100. return true;
  101. }
  102. /**
  103. * 根据二维码编号写入文件流到指定路径
  104. * @param qrcode
  105. * @return
  106. * @throws Exception
  107. */
  108. public static boolean generateQRCodeImage(String filePath,String qrcode) throws Exception{
  109. if(StringUtils.isEmpty(qrcode)){
  110. return false;
  111. }
  112. FileOutputStream outputStream=new FileOutputStream(filePath);
  113. generateStreamFile(qrcode, outputStream);
  114. return true;
  115. }
  116. /**
  117. * 服务器文件——生成流式二维码
  118. *
  119. * @param qParam
  120. * @param content
  121. * @param outputStream
  122. * @throws WriterException
  123. * @throws IOException
  124. */
  125. private static void generateStreamFile(String content,OutputStream outputStream) throws WriterException, IOException {
  126. String baseUrl = ConfigUtil.getConfig("google.zxing.url");
  127. int width = Integer
  128. .parseInt(ConfigUtil.getConfig("google.zxing.width"));
  129. int height = Integer.parseInt(ConfigUtil
  130. .getConfig("google.zxing.height"));
  131. String format = ConfigUtil.getConfig("google.zxing.format");
  132. String qrContent = baseUrl + "/showPage.do?GSBH=" + content;
  133. Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
  134. // 指定编码格式
  135. hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
  136. // 指定纠错级别(L--7%,M--15%,Q--25%,H--30%)
  137. hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
  138. // 编码内容,编码类型(这里指定为二维码),生成图片宽度,生成图片高度,设置参数
  139. BitMatrix bitMatrix = new MultiFormatWriter().encode(qrContent,BarcodeFormat.QR_CODE, width, height, hints);
  140. MatrixToImageWriter.writeToStream(bitMatrix, format, outputStream);
  141. outputStream.flush();
  142. outputStream.close();
  143. }
  144. /**
  145. * 浏览器响应——生成流式二维码
  146. *
  147. * @param qParam
  148. * @param content
  149. * @param response
  150. * @throws WriterException
  151. * @throws IOException
  152. */
  153. public static void generateStreamFileForBrowser(String content,
  154. HttpServletResponse response) throws WriterException, IOException {
  155. String baseUrl = ConfigUtil.getConfig("google.zxing.url");
  156. int width = Integer
  157. .parseInt(ConfigUtil.getConfig("google.zxing.width"));
  158. int height = Integer.parseInt(ConfigUtil
  159. .getConfig("google.zxing.height"));
  160. String format = ConfigUtil.getConfig("google.zxing.format");
  161. String qrContent = baseUrl + "/showPage.do?GSBH=" + content;
  162. Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
  163. // 指定编码格式
  164. hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
  165. // 指定纠错级别(L--7%,M--15%,Q--25%,H--30%)
  166. hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
  167. // 编码内容,编码类型(这里指定为二维码),生成图片宽度,生成图片高度,设置参数
  168. BitMatrix bitMatrix = new MultiFormatWriter().encode(qrContent,
  169. BarcodeFormat.QR_CODE, width, height, hints);
  170. // 设置请求头
  171. response.setHeader("Content-Type", "application/octet-stream");
  172. response.setHeader("Content-Disposition", "attachment;filename="
  173. + content + "." + format);
  174. OutputStream outputStream = response.getOutputStream();
  175. MatrixToImageWriter.writeToStream(bitMatrix, format, outputStream);
  176. outputStream.flush();
  177. outputStream.close();
  178. }
  179. }

图片压缩下载工具

FileZipUtils.java

  1. package com.boonya.util;
  2. import javax.servlet.http.HttpServletResponse;
  3. import java.io.*;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import java.util.zip.ZipEntry;
  7. import java.util.zip.ZipOutputStream;
  8. /**
  9. * @ClassName: FileZipUtils
  10. * @Description: TODO(功能说明:文件压缩及下载)
  11. * @author: pengjunlin
  12. * @motto: 学习需要毅力,那就秀毅力
  13. * @date 2019/10/16 23:23
  14. */
  15. public class FileZipUtils {
  16. /**
  17. * 把文件打成压缩包并保存在本地硬盘
  18. */
  19. public static void saveZipFiles(List<String> srcfiles, String zipFilePath, String zipFileName) {
  20. try {
  21. // 创建文件夹
  22. File file = new File(zipFilePath);
  23. if (!file.exists()) {
  24. file.mkdirs();
  25. }
  26. // 创建zip输出流
  27. ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilePath + File.separator + zipFileName));
  28. // 循环将源文件列表添加到zip文件中
  29. zipFile(srcfiles, zos);
  30. } catch (IOException e) {
  31. e.printStackTrace();
  32. }
  33. }
  34. /**
  35. * 把文件打成压缩包并输出到客户端浏览器中
  36. */
  37. public static void downloadZipFiles(HttpServletResponse response, List<String> srcFiles, String zipFileName) {
  38. try {
  39. response.reset(); // 重点突出
  40. response.setCharacterEncoding("UTF-8"); // 重点突出ss
  41. response.setContentType("application/x-msdownload"); // 不同类型的文件对应不同的MIME类型 // 重点突出
  42. // 对文件名进行编码处理中文问题
  43. zipFileName = new String(zipFileName.getBytes(), "UTF-8");
  44. // inline在浏览器中直接显示,不提示用户下载
  45. // attachment弹出对话框,提示用户进行下载保存本地
  46. // 默认为inline方式
  47. response.setHeader("Content-Disposition", "attachment;filename=" + zipFileName);
  48. // --设置成这样可以不用保存在本地,再输出, 通过response流输出,直接输出到客户端浏览器中。
  49. ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
  50. zipFile(srcFiles, zos);
  51. } catch (IOException e) {
  52. e.printStackTrace();
  53. }
  54. }
  55. /**
  56. * 压缩文件
  57. *
  58. * @param filePaths 需要压缩的文件路径集合
  59. * @throws IOException
  60. */
  61. private static void zipFile(List<String> filePaths, ZipOutputStream zos) {
  62. //设置读取数据缓存大小
  63. byte[] buffer = new byte[4096];
  64. try {
  65. //循环读取文件路径集合,获取每一个文件的路径
  66. for (String filePath : filePaths) {
  67. File inputFile = new File(filePath);
  68. //判断文件是否存在
  69. if (inputFile.exists()) {
  70. //判断是否属于文件,还是文件夹
  71. if (inputFile.isFile()) {
  72. //创建输入流读取文件
  73. BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inputFile));
  74. //将文件写入zip内,即将文件进行打包
  75. zos.putNextEntry(new ZipEntry(inputFile.getName()));
  76. //写入文件的方法,同上
  77. int size = 0;
  78. //设置读取数据缓存大小
  79. while ((size = bis.read(buffer)) > 0) {
  80. zos.write(buffer, 0, size);
  81. }
  82. //关闭输入输出流
  83. zos.closeEntry();
  84. bis.close();
  85. } else { //如果是文件夹,则使用穷举的方法获取文件,写入zip
  86. File[] files = inputFile.listFiles();
  87. List<String> filePathsTem = new ArrayList<String>();
  88. for (File fileTem : files) {
  89. filePathsTem.add(fileTem.toString());
  90. }
  91. zipFile(filePathsTem, zos);
  92. }
  93. }
  94. }
  95. } catch (IOException e) {
  96. e.printStackTrace();
  97. } finally {
  98. if (null != zos) {
  99. try {
  100. zos.close();
  101. } catch (IOException e) {
  102. e.printStackTrace();
  103. }
  104. }
  105. }
  106. }
  107. /**
  108. * 删除指定文件或文件夹下所有文件
  109. *
  110. * @param path 文件夹完整绝对路径
  111. * @return
  112. */
  113. public static boolean delAllFile(String path) {
  114. File file = new File(path);
  115. if (!file.exists()) {
  116. return false;
  117. }
  118. if (file.isFile()) {
  119. return file.delete();
  120. }
  121. if (file.isDirectory()) {
  122. String[] fileList = file.list();
  123. String tempFilePath = null;
  124. for (String tempFileName : fileList) {
  125. if (path.endsWith(File.separator)) {
  126. tempFilePath = path + tempFileName;
  127. } else {
  128. tempFilePath = path + File.separator + tempFileName;
  129. }
  130. delAllFile(tempFilePath);
  131. }
  132. file.delete();
  133. }
  134. return true;
  135. }
  136. }

二维码控制器

QRCodeController.java

  1. package com.boonya.controller;
  2. import java.io.File;
  3. import java.text.SimpleDateFormat;
  4. import java.util.ArrayList;
  5. import java.util.Date;
  6. import java.util.HashMap;
  7. import java.util.List;
  8. import java.util.Map;
  9. import javax.servlet.http.HttpServletRequest;
  10. import javax.servlet.http.HttpServletResponse;
  11. import org.apache.log4j.Logger;
  12. import org.springframework.beans.factory.annotation.Autowired;
  13. import org.springframework.stereotype.Controller;
  14. import org.springframework.web.bind.annotation.RequestMapping;
  15. import org.springframework.web.bind.annotation.ResponseBody;
  16. import com.alibaba.fastjson.JSONArray;
  17. import com.alibaba.fastjson.JSONObject;
  18. import com.boonya.core.util.StringUtils;
  19. import com.boonya.data.general.QueryFilter;
  20. import com.boonya.data.general.RowBase;
  21. import com.boonya.data.service.BaseService;
  22. import com.boonya.util.FileGenerateUtils;
  23. import com.boonya.util.FileZipUtils;
  24. /**
  25. *
  26. * @function 功能:二维码工具类(/RestService为不拦截地址)
  27. * @author PJL
  28. * @package com.boonya.controller
  29. * @filename QRCodeController.java
  30. * @time 2019 2019年9月25日 上午10:41:25
  31. */
  32. @Controller
  33. public class QRCodeController {
  34. @Autowired
  35. BaseService baseDataService;
  36. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
  37. private static Logger logger = Logger.getLogger(QRCodeController.class);
  38. /**
  39. * 流式二维码地址
  40. *
  41. * @param request
  42. * @param response
  43. * @throws Exception
  44. */
  45. @RequestMapping("/RestService/qrcode/downloadSingle.do")
  46. public void download(HttpServletRequest request,
  47. HttpServletResponse response) throws Exception {
  48. logger.info(">>>download single QRCode Image from browser.");
  49. // 二维码中包含的信息
  50. String content = request.getParameter("content");
  51. if (StringUtils.isEmpty(content)) {
  52. content = sdf.format(new Date());
  53. logger.info(">>>download a date param QRCode Image from browser.");
  54. }
  55. FileGenerateUtils.generateStreamFileForBrowser(content, response);
  56. }
  57. /**
  58. * 获取二维码图片列表
  59. * @param rows
  60. * @param srcFiles
  61. * @throws Exception
  62. */
  63. @SuppressWarnings({ "rawtypes", "unchecked" })
  64. private void getQRCodeImageSrcList(List<RowBase> rows,List<String> srcFiles) throws Exception{
  65. if(null==rows){
  66. return ;
  67. }
  68. File file=null;
  69. RowBase row=null;
  70. for (RowBase rowBase : rows) {
  71. String gsbh=(String) rowBase.getOriginalObjects().get("GSBH");
  72. String ewm=(String) rowBase.getOriginalObjects().get("EWM");
  73. String filePath=FileGenerateUtils.getFilePath(gsbh);
  74. file=new File(filePath);
  75. if(!file.exists()){
  76. // 生成已审核的记录的二维码==监测记录不存在文件重新生成
  77. FileGenerateUtils.generateQRCodeImage(filePath, gsbh);
  78. /**更新二维码字段----S***/
  79. String relativePath=FileGenerateUtils.getRelativePath(gsbh);
  80. HashMap<String,Object> oriMap = new HashMap<String, Object>();//历史map
  81. oriMap.put("PK_UID",Long.valueOf(rowBase.getOriginalObjects().get("PK_UID").toString()));
  82. HashMap<String,Object> curMap = new HashMap<String, Object>();//当前map
  83. curMap.put("EWM", relativePath);
  84. row = new RowBase();
  85. row.setOriginalObjects(oriMap);
  86. row.setCurrentObjects(curMap);
  87. baseDataService.save("HNGS_GSMM_PT", row);
  88. /**更新二维码字段----E***/
  89. }
  90. srcFiles.add(filePath);
  91. }
  92. }
  93. /**
  94. * 批量导出二维码文件(ZIP压缩文件)
  95. *
  96. * @param request
  97. * @param response
  98. * @throws Exception
  99. */
  100. @SuppressWarnings({ "rawtypes" })
  101. @RequestMapping("/RestService/qrcode/downloadZip.do")
  102. public void downloadZip(HttpServletRequest request,
  103. HttpServletResponse response) throws Exception {
  104. logger.info(">>>download zip QRCode Image from browser.");
  105. String zipFileName=sdf.format(new Date())+".zip";
  106. String IDS = request.getParameter("IDS");
  107. IDS=IDS==null?"[]":IDS;// 设置ID为空
  108. List<String> srcFiles=new ArrayList<String>();
  109. JSONArray jsonArray=JSONObject.parseArray(IDS);
  110. StringBuffer sb=new StringBuffer();
  111. for (int i = 0,j=jsonArray.size(); i < j; i++) {
  112. if(i==0){
  113. sb.append(jsonArray.get(i).toString());
  114. }else{
  115. sb.append(",").append(jsonArray.get(i).toString());
  116. }
  117. }
  118. String checkdIds=sb.toString();
  119. QueryFilter filter=new QueryFilter();
  120. filter.setSelectFields("PK_UID,GSBH,EWM");
  121. if(checkdIds.length()>0){
  122. filter.setWhereString("SHZT='2' AND CZDB='2' AND CZJD='3' AND PK_UID IN ("+checkdIds+")");
  123. }else{
  124. filter.setWhereString("SHZT='2' AND CZDB='2' AND CZJD='3'");
  125. }
  126. List<RowBase> rows=baseDataService.getDataTable("HNGS_GSMM_PT", filter) ;
  127. getQRCodeImageSrcList(rows, srcFiles);
  128. if(srcFiles.size()>0){
  129. FileZipUtils.downloadZipFiles(response, srcFiles, zipFileName);
  130. }else{
  131. String errorTxt="没有查询到已审核记录,请请审核后再执行导出!";
  132. String fileName="UNEXCEPT_RESULT.txt";
  133. // 设置请求头
  134. response.setHeader("Content-Type", "application/txt");
  135. response.setHeader("Content-Disposition", "attachment;filename="+fileName);
  136. response.getOutputStream().write(errorTxt.getBytes());
  137. response.getOutputStream().flush();
  138. response.getOutputStream().close();
  139. }
  140. }
  141. /**
  142. * 生成二维码到服务器(支持单个、多个、所有)
  143. *
  144. * @param request
  145. * @param response
  146. * @throws Exception
  147. */
  148. @SuppressWarnings({ "rawtypes", "unchecked" })
  149. @RequestMapping("/RestService/qrcode/generateQRCode.do")
  150. @ResponseBody
  151. public Map<String, Object> generateQRCode(HttpServletRequest request,
  152. HttpServletResponse response) throws Exception {
  153. logger.info(">>>generate QRCode Image on server.");
  154. String IDS = request.getParameter("IDS");
  155. IDS=IDS==null?"[]":IDS;// 设置ID为空
  156. JSONArray jsonArray=JSONObject.parseArray(IDS);
  157. StringBuffer sb=new StringBuffer();
  158. for (int i = 0,j=jsonArray.size(); i < j; i++) {
  159. if(i==0){
  160. sb.append(jsonArray.get(i).toString());
  161. }else{
  162. sb.append(",").append(jsonArray.get(i).toString());
  163. }
  164. }
  165. String checkdIds=sb.toString();
  166. QueryFilter filter=new QueryFilter();
  167. filter.setSelectFields("PK_UID,GSBH,EWM");
  168. if(checkdIds.length()>0){
  169. filter.setWhereString("SHZT='2' AND CZDB='2' AND CZJD='3' AND PK_UID IN ("+checkdIds+")");
  170. }else{
  171. filter.setWhereString("SHZT='2' AND CZDB='2' AND CZJD='3'");
  172. }
  173. List<RowBase> rows=baseDataService.getDataTable("HNGS_GSMM_PT", filter) ;
  174. RowBase row=null;
  175. File file=null;
  176. List<String> gsbhList=new ArrayList<String>();
  177. List<String> fileList=new ArrayList<String>();
  178. for (RowBase rowBase : rows) {
  179. String gsbh=(String) rowBase.getOriginalObjects().get("GSBH");
  180. String filePath=FileGenerateUtils.getFilePath(gsbh);
  181. file=new File(filePath);
  182. boolean exists=true;
  183. if(!file.exists()){
  184. FileGenerateUtils.mkdirAndFile(gsbh);
  185. exists=false;
  186. }
  187. boolean success=FileGenerateUtils.generateQRCodeImage(filePath,gsbh);
  188. gsbhList.add(gsbh);
  189. if(success&&!exists){
  190. /**更新二维码字段----S***/
  191. String relativePath=FileGenerateUtils.getRelativePath(gsbh);
  192. HashMap<String,Object> oriMap = new HashMap<String, Object>();//历史map
  193. oriMap.put("PK_UID",Long.valueOf(rowBase.getOriginalObjects().get("PK_UID").toString()));
  194. HashMap<String,Object> curMap = new HashMap<String, Object>();//当前map
  195. curMap.put("EWM", relativePath);
  196. row = new RowBase();
  197. row.setOriginalObjects(oriMap);
  198. row.setCurrentObjects(curMap);
  199. baseDataService.save("HNGS_GSMM_PT", row);
  200. /**更新二维码字段----E***/
  201. fileList.add(relativePath);
  202. }
  203. }
  204. Map<String, Object> result = new HashMap<String, Object>();
  205. result.put("success",true );
  206. result.put("gsbhList", gsbhList);
  207. result.put("fileList", fileList);
  208. return result;
  209. }
  210. /**
  211. * 二维码信息跳转地址
  212. *
  213. * @param request
  214. * @param response
  215. * @throws Exception
  216. */
  217. @RequestMapping("/RestService/qrcode/showPage.do")
  218. public String showPage(HttpServletRequest request,
  219. HttpServletResponse response) throws Exception {
  220. logger.info(">>>scan QRCode Image transfer page.");
  221. String gsbh = request.getParameter("content");
  222. if (!StringUtils.isEmpty(gsbh)) {
  223. return "/qrcode/gsmm";
  224. } else {
  225. return "/qrcode/date";
  226. }
  227. }
  228. }

测试效果

生成二维码

注意:业务使用时注意存储路径写相对路径,可以使用NGINX代理访问

下载ZIP压缩文件

 

相关技术文章

点击QQ咨询
开通会员
返回顶部
×
微信扫码支付
微信扫码支付
确定支付下载
请使用微信描二维码支付
×

提示信息

×

选择支付方式

  • 微信支付
  • 支付宝付款
确定支付下载