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

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

目录

Zxing二维码生成工具

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

二维码图片生成工具

图片压缩下载工具

二维码控制器

测试效果

生成二维码

下载ZIP压缩文件


Zxing二维码生成工具

pom.xml


		
			com.google.zxing
			core
			3.3.3
		
		
			com.google.zxing
			javase
			3.3.3
		

QRCodeUtil.java

package com.boonya.util;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
 * 
 * @function 功能:二维码生成工具
 * @author   PJL
 * @package  com.forestar.util
 * @filename QRCodeUtil.java
 * @time     2019 2019年9月25日 上午11:32:55
 */
public class QRCodeUtil {
    private static int width = 300; // 二维码宽度
    private static int height = 300; // 二维码高度
    private static int onColor = 0xFF000000; // 前景色
    private static int offColor = 0xFFFFFFFF; // 背景色
    private static int margin = 1; // 白边大小,取值范围0~4
    private static ErrorCorrectionLevel level = ErrorCorrectionLevel.L; // 二维码容错率

    /**
     * 生成二维码
     * 
     * @param params
     *            QRCodeParams属性:txt、fileName、filePath不得为空;
     * @throws Exception
     */
    public static void generateQRImage(QRCodeParams params)
	    throws Exception {
	if (params == null || params.getFileName() == null
		|| params.getFilePath() == null || params.getTxt() == null) {

	    throw new Exception("二维码参数错误");
	}
	try {
	    initData(params);

	    String imgPath = params.getFilePath();
	    String imgName = params.getFileName();
	    String txt = params.getTxt();

	    if (params.getLogoPath() != null
		    && !"".equals(params.getLogoPath().trim())) {
		generateQRImage(txt, params.getLogoPath(), imgPath, imgName,
			params.getSuffixName());
	    } else {
		generateQRImage(txt, imgPath, imgName, params.getSuffixName());
	    }
	} catch (Exception e) {
	    e.printStackTrace();
	}

    }

    /**
     * 生成二维码
     * 
     * @param txt
     *            //二维码内容
     * @param imgPath
     *            //二维码保存物理路径
     * @param imgName
     *            //二维码文件名称
     * @param suffix
     *            //图片后缀名
     */
    public static void generateQRImage(String txt, String imgPath,
	    String imgName, String suffix) {

	File filePath = new File(imgPath);
	if (!filePath.exists()) {
	    filePath.mkdirs();
	}

	File imageFile = new File(imgPath, imgName);
	Hashtable hints = new Hashtable();
	// 指定纠错等级
	hints.put(EncodeHintType.ERROR_CORRECTION, level);
	// 指定编码格式
	hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
	hints.put(EncodeHintType.MARGIN, margin); // 设置白边
	try {
	    MatrixToImageConfig config = new MatrixToImageConfig(onColor,
		    offColor);
	    BitMatrix bitMatrix = new MultiFormatWriter().encode(txt,
		    BarcodeFormat.QR_CODE, width, height, hints);
	    // bitMatrix = deleteWhite(bitMatrix);
	    MatrixToImageWriter.writeToPath(bitMatrix, suffix,
		    imageFile.toPath(), config);
	} catch (Exception e) {
	    e.printStackTrace();
	}
    }

    /**
     * 生成带logo的二维码图片
     * 
     * @param txt
     *            //二维码内容
     * @param logoPath
     *            //logo绝对物理路径
     * @param imgPath
     *            //二维码保存绝对物理路径
     * @param imgName
     *            //二维码文件名称
     * @param suffix
     *            //图片后缀名
     * @throws Exception
     */
    public static void generateQRImage(String txt, String logoPath,
	    String imgPath, String imgName, String suffix) throws Exception {

	File filePath = new File(imgPath);
	if (!filePath.exists()) {
	    filePath.mkdirs();
	}

	if (imgPath.endsWith("/")) {
	    imgPath += imgName;
	} else {
	    imgPath += "/" + imgName;
	}

	Hashtable hints = new Hashtable();
	hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
	hints.put(EncodeHintType.ERROR_CORRECTION, level);
	hints.put(EncodeHintType.MARGIN, margin); // 设置白边
	BitMatrix bitMatrix = new MultiFormatWriter().encode(txt,
		BarcodeFormat.QR_CODE, width, height, hints);
	File qrcodeFile = new File(imgPath);
	writeToFile(bitMatrix, suffix, qrcodeFile, logoPath);
    }

    /**
     * 
     * @param matrix
     *            二维码矩阵相关
     * @param format
     *            二维码图片格式
     * @param file
     *            二维码图片文件
     * @param logoPath
     *            logo路径
     * @throws IOException
     */
    public static void writeToFile(BitMatrix matrix, String format, File file,
	    String logoPath) throws IOException {
	BufferedImage image = toBufferedImage(matrix);
	Graphics2D gs = image.createGraphics();

	int ratioWidth = image.getWidth() * 2 / 10;
	int ratioHeight = image.getHeight() * 2 / 10;
	// 载入logo
	Image img = ImageIO.read(new File(logoPath));
	int logoWidth = img.getWidth(null) > ratioWidth ? ratioWidth : img
		.getWidth(null);
	int logoHeight = img.getHeight(null) > ratioHeight ? ratioHeight : img
		.getHeight(null);

	int x = (image.getWidth() - logoWidth) / 2;
	int y = (image.getHeight() - logoHeight) / 2;

	gs.drawImage(img, x, y, logoWidth, logoHeight, null);
	gs.setColor(Color.black);
	gs.setBackground(Color.WHITE);
	gs.dispose();
	img.flush();
	if (!ImageIO.write(image, format, file)) {
	    throw new IOException("Could not write an image of format "
		    + format + " to " + file);
	}
    }

    public static BufferedImage toBufferedImage(BitMatrix matrix) {
	int width = matrix.getWidth();
	int height = matrix.getHeight();
	BufferedImage 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, matrix.get(x, y) ? onColor : offColor);
	    }
	}
	return image;
    }

    public static BitMatrix deleteWhite(BitMatrix matrix) {
	int[] rec = matrix.getEnclosingRectangle();
	int resWidth = rec[2] + 1;
	int resHeight = rec[3] + 1;

	BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
	resMatrix.clear();
	for (int i = 0; i < resWidth; i++) {
	    for (int j = 0; j < resHeight; j++) {
		if (matrix.get(i + rec[0], j + rec[1]))
		    resMatrix.set(i, j);
	    }
	}
	return resMatrix;
    }

    private static void initData(QRCodeParams params) {
	if (params.getWidth() != null) {
	    width = params.getWidth();
	}
	if (params.getHeight() != null) {
	    height = params.getHeight();
	}
	if (params.getOnColor() != null) {
	    onColor = params.getOnColor();
	}
	if (params.getOffColor() != null) {
	    offColor = params.getOffColor();
	}
	if (params.getLevel() != null) {
	    level = params.getLevel();
	}

    }

}

QRCodeParams.java

package com.boonya.util;

import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
 * 
 * @function 功能:二维码设置参数
 * @author   PJL
 * @package  com.forestar.util
 * @filename QRCodeParams.java
 * @time     2019 2019年9月25日 上午11:00:17
 */
public class QRCodeParams {

    private String txt; // 二维码内容
    private String qrCodeUrl; // 二维码网络路径
    private String filePath; // 二维码生成物理路径
    private String fileName; // 二维码生成图片名称(包含后缀名)
    private String logoPath; // logo图片
    private Integer width = 300; // 二维码宽度
    private Integer height = 300; // 二维码高度
    private Integer onColor = 0xFF000000; // 前景色
    private Integer offColor = 0xFFFFFFFF; // 背景色
    private Integer margin = 1; // 白边大小,取值范围0~4
    private ErrorCorrectionLevel level = ErrorCorrectionLevel.L; // 二维码容错率

    public String getTxt() {
	return txt;
    }

    public void setTxt(String txt) {
	this.txt = txt;
    }

    public String getFilePath() {
	return filePath;
    }

    public void setFilePath(String filePath) {
	this.filePath = filePath;
    }

    public String getFileName() {
	return fileName;
    }

    public void setFileName(String fileName) {
	this.fileName = fileName;
    }

    public Integer getWidth() {
	return width;
    }

    public void setWidth(Integer width) {
	this.width = width;
    }

    public Integer getHeight() {
	return height;
    }

    public void setHeight(Integer height) {
	this.height = height;
    }

    public String getQrCodeUrl() {
	return qrCodeUrl;
    }

    public void setQrCodeUrl(String qrCodeUrl) {
	this.qrCodeUrl = qrCodeUrl;
    }

    public String getLogoPath() {
	return logoPath;
    }

    public void setLogoPath(String logoPath) {
	this.logoPath = logoPath;
    }

    public Integer getOnColor() {
	return onColor;
    }

    public void setOnColor(Integer onColor) {
	this.onColor = onColor;
    }

    public Integer getOffColor() {
	return offColor;
    }

    public void setOffColor(Integer offColor) {
	this.offColor = offColor;
    }

    public ErrorCorrectionLevel getLevel() {
	return level;
    }

    public void setLevel(ErrorCorrectionLevel level) {
	this.level = level;
    }

    /**
     * 返回文件后缀名
     * 
     * @return
     */
    public String getSuffixName() {
	String imgName = this.getFileName();
	if (imgName != null && !"".equals(imgName)) {
	    String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
	    return suffix;
	}
	return "";
    }

    public Integer getMargin() {
	return margin;
    }

    public void setMargin(Integer margin) {
	this.margin = margin;
    }

}

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

二维码图片生成工具

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

package com.boonya.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import com.boonya.core.util.StringUtils;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
 * @function 功能:二维码文件生成到指定路径
 * @author   PJL
 * @package  com.boonya.util
 * @filename FileGenerateUtils.java
 * @time     2019 2019年10月21日 下午1:07:52
 */
public class FileGenerateUtils {
	
	private static String FILE_SERVER_ADDRESS="";
	
	static{
		try {
			FILE_SERVER_ADDRESS = FileGenerateUtils.class.getResource("").toURI().getPath();
		} catch (URISyntaxException e) {
			e.printStackTrace();
		}
		FILE_SERVER_ADDRESS = FILE_SERVER_ADDRESS.substring(0,FILE_SERVER_ADDRESS.lastIndexOf("/WEB-INF/") + 1);
		if(!FILE_SERVER_ADDRESS.endsWith("/")){
			FILE_SERVER_ADDRESS+="/";
		}
	}
	
	/**
	 * 获取文件基础路径
	 * 
	 * @return
	 */
	public static String getBasePath(){
		return FILE_SERVER_ADDRESS;
	}
	
	/**
	 * 获取相对路径
	 * @param qrcode
	 * @return
	 */
	public static String getRelativePath(String qrcode){
		String sheng=qrcode.substring(0,2);
		String shi=qrcode.substring(0,4);
		String xian=qrcode.substring(0,6);
		return "/qrcode/"+sheng+"/"+shi+"/"+xian+"/"+qrcode+".png";
	}
	
	/**
	 * 获取固定规则的文件路径
	 * @param qrcode
	 * @return
	 */
	public static String getFilePath(String qrcode){
		String sheng=qrcode.substring(0,2);
		String shi=qrcode.substring(0,4);
		String xian=qrcode.substring(0,6);
		File xianPath=new File(FILE_SERVER_ADDRESS+"qrcode/"+sheng+"/"+shi+"/"+xian);
		if(!xianPath.exists()){
			xianPath.mkdirs();
		}
		String filePath=xianPath.getPath()+"/"+qrcode+".png";
		return filePath;
	}
	
	/**
	 * 创建二维码路径和文件
	 * 
	 * @param qrcode
	 * @throws Exception 
	 */
	public static String mkdirAndFile(String qrcode) throws Exception{
		String filePath=getFilePath(qrcode);
		File path=new File(filePath);
		if(!path.exists()){
			path.createNewFile();
		}
		return filePath;
	}
	
	/**
	 * 根据二维码编号写入文件流到指定路径
	 * @param qrcode
	 * @return
	 * @throws Exception
	 */
	public static boolean generateQRCodeImage(String qrcode) throws Exception{
		if(StringUtils.isEmpty(qrcode)){
			return false;
		}
		String filePath=mkdirAndFile(qrcode);
		FileOutputStream outputStream=new FileOutputStream(filePath); 
		generateStreamFile(qrcode, outputStream);
		return true;
	}
	
	/**
	 * 根据二维码编号写入文件流到指定路径
	 * @param qrcode
	 * @return
	 * @throws Exception
	 */
	public static boolean generateQRCodeImage(String filePath,String qrcode) throws Exception{
		if(StringUtils.isEmpty(qrcode)){
			return false;
		}
		FileOutputStream outputStream=new FileOutputStream(filePath); 
		generateStreamFile(qrcode, outputStream);
		return true;
	}
	
	
	/**
	 * 服务器文件——生成流式二维码
	 * 
	 * @param qParam
	 * @param content
	 * @param outputStream
	 * @throws WriterException
	 * @throws IOException
	 */
	private static void generateStreamFile(String content,OutputStream outputStream) throws WriterException, IOException {
		String baseUrl = ConfigUtil.getConfig("google.zxing.url");
		int width = Integer
				.parseInt(ConfigUtil.getConfig("google.zxing.width"));
		int height = Integer.parseInt(ConfigUtil
				.getConfig("google.zxing.height"));
		String format = ConfigUtil.getConfig("google.zxing.format");
		String qrContent = baseUrl + "/showPage.do?GSBH=" + content;
		Map 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(qrContent,BarcodeFormat.QR_CODE, width, height, hints);
		MatrixToImageWriter.writeToStream(bitMatrix, format, outputStream);
		outputStream.flush();
		outputStream.close();
	}
	
	
	/**
	 * 浏览器响应——生成流式二维码
	 * 
	 * @param qParam
	 * @param content
	 * @param response
	 * @throws WriterException
	 * @throws IOException
	 */
	public static void generateStreamFileForBrowser(String content,
			HttpServletResponse response) throws WriterException, IOException {
		String baseUrl = ConfigUtil.getConfig("google.zxing.url");
		int width = Integer
				.parseInt(ConfigUtil.getConfig("google.zxing.width"));
		int height = Integer.parseInt(ConfigUtil
				.getConfig("google.zxing.height"));
		String format = ConfigUtil.getConfig("google.zxing.format");
		String qrContent = baseUrl + "/showPage.do?GSBH=" + content;
		Map 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(qrContent,
				BarcodeFormat.QR_CODE, width, height, hints);
		// 设置请求头
		response.setHeader("Content-Type", "application/octet-stream");
		response.setHeader("Content-Disposition", "attachment;filename="
				+ content + "." + format);
		OutputStream outputStream = response.getOutputStream();
		MatrixToImageWriter.writeToStream(bitMatrix, format, outputStream);
		outputStream.flush();
		outputStream.close();
	}

}

图片压缩下载工具

FileZipUtils.java

package com.boonya.util;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @ClassName: FileZipUtils
 * @Description: TODO(功能说明:文件压缩及下载)
 * @author: pengjunlin
 * @motto: 学习需要毅力,那就秀毅力
 * @date 2019/10/16 23:23
 */
public class FileZipUtils {

    /**
     * 把文件打成压缩包并保存在本地硬盘
     */
    public static void saveZipFiles(List srcfiles, String zipFilePath, String zipFileName) {
        try {
            // 创建文件夹
            File file = new File(zipFilePath);
            if (!file.exists()) {
                file.mkdirs();
            }
            // 创建zip输出流
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFilePath + File.separator + zipFileName));
            // 循环将源文件列表添加到zip文件中
            zipFile(srcfiles, zos);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 把文件打成压缩包并输出到客户端浏览器中
     */
    public static void downloadZipFiles(HttpServletResponse response, List srcFiles, String zipFileName) {
        try {
            response.reset(); // 重点突出
            response.setCharacterEncoding("UTF-8"); // 重点突出ss
            response.setContentType("application/x-msdownload"); // 不同类型的文件对应不同的MIME类型 // 重点突出
            // 对文件名进行编码处理中文问题
            zipFileName = new String(zipFileName.getBytes(), "UTF-8");
            // inline在浏览器中直接显示,不提示用户下载
            // attachment弹出对话框,提示用户进行下载保存本地
            // 默认为inline方式
            response.setHeader("Content-Disposition", "attachment;filename=" + zipFileName);

            // --设置成这样可以不用保存在本地,再输出, 通过response流输出,直接输出到客户端浏览器中。
            ZipOutputStream zos = new ZipOutputStream(response.getOutputStream());
            zipFile(srcFiles, zos);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 压缩文件
     *
     * @param filePaths 需要压缩的文件路径集合
     * @throws IOException
     */
    private static void zipFile(List filePaths, ZipOutputStream zos) {
        //设置读取数据缓存大小
        byte[] buffer = new byte[4096];
        try {
            //循环读取文件路径集合,获取每一个文件的路径
            for (String filePath : filePaths) {
                File inputFile = new File(filePath);
                //判断文件是否存在
                if (inputFile.exists()) {
                    //判断是否属于文件,还是文件夹
                    if (inputFile.isFile()) {
                        //创建输入流读取文件
                        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(inputFile));
                        //将文件写入zip内,即将文件进行打包
                        zos.putNextEntry(new ZipEntry(inputFile.getName()));
                        //写入文件的方法,同上
                        int size = 0;
                        //设置读取数据缓存大小
                        while ((size = bis.read(buffer)) > 0) {
                            zos.write(buffer, 0, size);
                        }
                        //关闭输入输出流
                        zos.closeEntry();
                        bis.close();
                    } else {  //如果是文件夹,则使用穷举的方法获取文件,写入zip
                        File[] files = inputFile.listFiles();
                        List filePathsTem = new ArrayList();
                        for (File fileTem : files) {
                            filePathsTem.add(fileTem.toString());
                        }
                        zipFile(filePathsTem, zos);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != zos) {
                try {
                    zos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 删除指定文件或文件夹下所有文件
     *
     * @param path 文件夹完整绝对路径
     * @return
     */
    public static boolean delAllFile(String path) {
        File file = new File(path);
        if (!file.exists()) {
            return false;
        }
        if (file.isFile()) {
            return file.delete();
        }
        if (file.isDirectory()) {
            String[] fileList = file.list();
            String tempFilePath = null;
            for (String tempFileName : fileList) {
                if (path.endsWith(File.separator)) {
                    tempFilePath = path + tempFileName;
                } else {
                    tempFilePath = path + File.separator + tempFileName;
                }
                delAllFile(tempFilePath);
            }
            file.delete();
        }
        return true;
    }

}

二维码控制器

QRCodeController.java

package com.boonya.controller;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.boonya.core.util.StringUtils;
import com.boonya.data.general.QueryFilter;
import com.boonya.data.general.RowBase;
import com.boonya.data.service.BaseService;
import com.boonya.util.FileGenerateUtils;
import com.boonya.util.FileZipUtils;

/**
 * 
 * @function 功能:二维码工具类(/RestService为不拦截地址)
 * @author PJL
 * @package com.boonya.controller
 * @filename QRCodeController.java
 * @time 2019 2019年9月25日 上午10:41:25
 */
@Controller
public class QRCodeController {
	
	@Autowired
	BaseService baseDataService;

	
	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");

	private static Logger logger = Logger.getLogger(QRCodeController.class);


	/**
	 * 流式二维码地址
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/RestService/qrcode/downloadSingle.do")
	public void download(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		logger.info(">>>download single QRCode Image from browser.");
		// 二维码中包含的信息
		String content = request.getParameter("content");
		if (StringUtils.isEmpty(content)) {
			content = sdf.format(new Date());
			logger.info(">>>download a date param QRCode Image from browser.");
		}
		FileGenerateUtils.generateStreamFileForBrowser(content, response);
	}
	
	/**
	 * 获取二维码图片列表
	 * @param rows
	 * @param srcFiles
	 * @throws Exception
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void getQRCodeImageSrcList(List rows,List srcFiles) throws Exception{
		if(null==rows){
			return ;
		}
		File file=null;
		RowBase row=null;
		for (RowBase rowBase : rows) {
			String gsbh=(String) rowBase.getOriginalObjects().get("GSBH");
			String ewm=(String) rowBase.getOriginalObjects().get("EWM");
			String filePath=FileGenerateUtils.getFilePath(gsbh);
			file=new File(filePath);
			if(!file.exists()){
				// 生成已审核的记录的二维码==监测记录不存在文件重新生成
				FileGenerateUtils.generateQRCodeImage(filePath, gsbh);
				/**更新二维码字段----S***/
				String relativePath=FileGenerateUtils.getRelativePath(gsbh);
				HashMap oriMap = new HashMap();//历史map
				oriMap.put("PK_UID",Long.valueOf(rowBase.getOriginalObjects().get("PK_UID").toString()));
				HashMap curMap = new HashMap();//当前map
				curMap.put("EWM", relativePath);
				row = new RowBase();
				row.setOriginalObjects(oriMap);
				row.setCurrentObjects(curMap);
				baseDataService.save("HNGS_GSMM_PT", row);
				/**更新二维码字段----E***/
			}
			srcFiles.add(filePath);
		}
	}
	

	
	/**
	 * 批量导出二维码文件(ZIP压缩文件)
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@SuppressWarnings({ "rawtypes" })
	@RequestMapping("/RestService/qrcode/downloadZip.do")
	public void downloadZip(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		logger.info(">>>download zip QRCode Image from browser.");
		String zipFileName=sdf.format(new Date())+".zip";
		String IDS = request.getParameter("IDS");
		IDS=IDS==null?"[]":IDS;// 设置ID为空
		List srcFiles=new ArrayList();
		JSONArray jsonArray=JSONObject.parseArray(IDS);
		StringBuffer sb=new StringBuffer();
		for (int i = 0,j=jsonArray.size(); i < j; i++) {
			if(i==0){
				sb.append(jsonArray.get(i).toString());
			}else{
				sb.append(",").append(jsonArray.get(i).toString());
			}
		}
		String checkdIds=sb.toString();
		QueryFilter filter=new QueryFilter();
		filter.setSelectFields("PK_UID,GSBH,EWM");
		if(checkdIds.length()>0){
			filter.setWhereString("SHZT='2'  AND CZDB='2' AND CZJD='3' AND PK_UID IN ("+checkdIds+")");
		}else{
			filter.setWhereString("SHZT='2'  AND CZDB='2' AND CZJD='3'");
		}
		List rows=baseDataService.getDataTable("HNGS_GSMM_PT", filter) ;
		getQRCodeImageSrcList(rows, srcFiles);
		if(srcFiles.size()>0){
			FileZipUtils.downloadZipFiles(response, srcFiles, zipFileName);
		}else{
			String errorTxt="没有查询到已审核记录,请请审核后再执行导出!";
			String fileName="UNEXCEPT_RESULT.txt";
			// 设置请求头
			response.setHeader("Content-Type", "application/txt");
			response.setHeader("Content-Disposition", "attachment;filename="+fileName);
			response.getOutputStream().write(errorTxt.getBytes());
			response.getOutputStream().flush();
			response.getOutputStream().close();
		}
	}
	
	/**
	 * 生成二维码到服务器(支持单个、多个、所有)
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	@RequestMapping("/RestService/qrcode/generateQRCode.do")
	@ResponseBody
	public  Map  generateQRCode(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		 logger.info(">>>generate QRCode Image on server.");
		 String IDS = request.getParameter("IDS");
		 IDS=IDS==null?"[]":IDS;// 设置ID为空
		 JSONArray jsonArray=JSONObject.parseArray(IDS);
		 StringBuffer sb=new StringBuffer();
		 for (int i = 0,j=jsonArray.size(); i < j; i++) {
			if(i==0){
				sb.append(jsonArray.get(i).toString());
			}else{
				sb.append(",").append(jsonArray.get(i).toString());
			}
		 }
		 String checkdIds=sb.toString();
		 QueryFilter filter=new QueryFilter();
		 filter.setSelectFields("PK_UID,GSBH,EWM");
		 if(checkdIds.length()>0){
			 filter.setWhereString("SHZT='2'  AND CZDB='2' AND CZJD='3' AND PK_UID IN ("+checkdIds+")");
		 }else{
			 filter.setWhereString("SHZT='2'  AND CZDB='2' AND CZJD='3'");
		 }
		 List rows=baseDataService.getDataTable("HNGS_GSMM_PT", filter) ;
		 RowBase row=null;
		 File file=null;
		 List gsbhList=new ArrayList();
		 List fileList=new ArrayList();
		 for (RowBase rowBase : rows) {
			String gsbh=(String) rowBase.getOriginalObjects().get("GSBH");
			String filePath=FileGenerateUtils.getFilePath(gsbh);
			file=new File(filePath);
			boolean exists=true;
			if(!file.exists()){
				FileGenerateUtils.mkdirAndFile(gsbh);
				exists=false;
			}
			boolean	success=FileGenerateUtils.generateQRCodeImage(filePath,gsbh);
			gsbhList.add(gsbh);
			if(success&&!exists){
				/**更新二维码字段----S***/
				String relativePath=FileGenerateUtils.getRelativePath(gsbh);
				HashMap oriMap = new HashMap();//历史map
				oriMap.put("PK_UID",Long.valueOf(rowBase.getOriginalObjects().get("PK_UID").toString()));
				HashMap curMap = new HashMap();//当前map
				curMap.put("EWM", relativePath);
				row = new RowBase();
				row.setOriginalObjects(oriMap);
				row.setCurrentObjects(curMap);
				baseDataService.save("HNGS_GSMM_PT", row);
				/**更新二维码字段----E***/
				fileList.add(relativePath);
			}
		 }
		 Map result = new HashMap();
		 result.put("success",true );
		 result.put("gsbhList", gsbhList);
		 result.put("fileList", fileList);
		 return result;
	}
	
	/**
	 * 二维码信息跳转地址
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/RestService/qrcode/showPage.do")
	public String showPage(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		logger.info(">>>scan QRCode Image transfer page.");
		String gsbh = request.getParameter("content");
		if (!StringUtils.isEmpty(gsbh)) {
			return "/qrcode/gsmm";
		} else {
			return "/qrcode/date";
		}
	}


}

测试效果

生成二维码

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

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

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

下载ZIP压缩文件

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

 

你可能感兴趣的:(Java)