zxing下载二维码

226 阅读3分钟

** 2019-12-05 17:19:50 **

今天改需求看到之前写的zxing二维码,记录一下。

Maven仓库

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.2.1</version>
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.0.0</version>
</dependency>

简单下载单张

/**
 * 下载二维码
 *
 * @param roomId 二维码中存放的的数据
 * @param request 
 * @param response
 * @throws IOException
 */
@GetMapping("/code/download/{roomId}")
@ApiOperation("二维码下载")
public void downloadCode(@PathVariable String roomId, HttpServletRequest request, HttpServletResponse response) throws IOException {
    if (roomId == null) {
        return;
    }
    // ---------加密内容------------
    // log.info("------------>要加密的数据roomId:{}", roomId);
    String content = Base64.getEncoder().encodeToString(roomId.toString().getBytes("UTF-8"));
    if (content != null && !"".equals(content)) {
        // ----------二维码设置----------
        // 图像宽度
        int width = 300;
        // 图像高度
        int height = 300;
        // 图像类型
        String format = "png";
        Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>(3);
        // 编码格式
        hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        // 设置容错等级
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
        // 设置边距默认是5
        hints.put(EncodeHintType.MARGIN, 2);
        BitMatrix bitMatrix = null;
        OutputStream outputStream = null;
        InputStream inputStream = null;
        try {
            bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
            BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix);
            // 二维码图片转化成字节数组
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            boolean write = ImageIO.write(image, format, out);
            inputStream = new ByteArrayInputStream(out.toByteArray());
            outputStream = response.getOutputStream();
            response.reset();
            // 设置文件头编码方式和文件名
            String date = LocalDate.now().toString();
            String fileName = "二维码" + date + ".png";
            response.setCharacterEncoding("UTF-8");
            // 如果是IE,通过URLEncoder对filename进行UTF8编码。而其他的浏览器(firefox、chrome、safari、opera),则要通过字节转换成ISO8859-1。
            if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");
            }
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
            byte[] bf = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bf)) > 0) {
                outputStream.write(bf, 0, len);
            }
        } catch (WriterException e) {
            e.printStackTrace();
        } finally {
            if (outputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }
}

注意

一般项目中请求接口需要带token的,下载时如果是直接请求下载接口,需要暴露接口。在配置文件中暴露

下载多个二维码,打包.zip包

/**
 * 获取到宿舍dormId --下载二维码zip包
 * 
 * @param dormId 业务查询的楼栋id
 * @param request
 * @param response
 * @return
 * @throws IOException
 */
@GetMapping("/download/{dormId}")
@ApiOperation("二维码下载")
public R downloadCode(@PathVariable String dormId, HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {
    Dormitory dormitory=dormitoryService.getById(dormId);
    //按宿舍楼id查询所有宿舍
    List<Room> roomIdList = roomService.getbyDormIdRoomAll(dormId);
    //按宿舍楼id查询所有床位
    List<Bunk> bunkList = bunkService.getByDormIdBunkAll(dormId);

    String realPath = request.getSession().getServletContext().getRealPath("/");
    //1 生成二维码
    String path = realPath + dormitory.getTowerName();
    File file = new File(path);
    if (!file.exists()) {
        file.mkdirs();
    }
    ///////////////每条线程的数据数量
    int threadSize = 200;
    // 总数据条数
    int dataSize2=bunkList.size();
    // 线程数
    int threadNum = dataSize2 / threadSize + 1;
    // 定义标记,过滤threadNum为整数
    boolean special = dataSize2 % threadSize == 0;

    // 创建一个线程池
    ExecutorService exec = Executors.newFixedThreadPool(threadNum);
    // 定义一个任务集合
    List<Callable<Integer>> tasks = new ArrayList<Callable<Integer>>();
    Callable<Integer> task = null;
    List<Bunk> bunkCall = null;
    ///////////////////////
    // 确定每条线程的数据
    for (int i = 0; i < threadNum; i++) {
        if (i == threadNum - 1) {
            if (special) {
                break;
            }
            bunkCall = bunkList.subList(threadSize * i, dataSize2);
        } else {
            bunkCall = bunkList.subList(threadSize * i, threadSize * (i + 1));
        }
        final List<Bunk> bunkListStr = bunkCall;
        task = new Callable<Integer>() {
            Integer count = 0;

            @Override
            public Integer call() throws Exception {
                    for (Bunk bunk : bunkListStr) {
                        QRCodeUtil.generateQRImage(
                                InspectionConstant.inspectionType.DORM_BED.toString() + "|" + bunk.getId(),
                                path + "/" + bunk.getRoomId() + "号宿舍" + bunk.getNumber() + "床位" + ".jpg",
                                null,bunk.getNumber()
                        );//生成二维码的方法
                    }
                    count++;
                return 1;
            }
        };
        // 这里提交的任务容器列表和返回的Future列表存在顺序对应的关系
        tasks.add(task);
    }
        //生成二维码
        QRCodeUtil.generateQRImage(
                InspectionConstant.inspectionType.DORM_TOWER.toString() + "|" + dormId,
                path + "/宿舍楼" + dormitory.getTowerName() + ".jpg",
                null,dormitory.getTowerName());
        for (Room x : roomIdList) {
            //生成二维码的方法
            QRCodeUtil.generateQRImage(
                    InspectionConstant.inspectionType.DORM_ROOM.toString() + "|" + x.getId(),
                    path + "/宿舍" + x.getNumber() + ".jpg",
                    null,x.getNumber()
            );
        }
        //开始执行线程任务
        List<Future<Integer>> results = exec.invokeAll(tasks);

    // 关闭线程池
    exec.shutdown();
    //2 生成zip文件
    ZipHelper.zipCompress(path, path + ".zip");
    //3 下载
    String zipFileName = path + ".zip";
    String filename =  dormitory.getTowerName()+ ".zip";
    //设置文件MIME类型
    response.setContentType("application/octet-stream");

    response.setCharacterEncoding("UTF-8");
    //设置Content-Disposition
    response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
    InputStream in = new FileInputStream(zipFileName);
    OutputStream out = response.getOutputStream();

    //写文件
    int b;
    while ((b = in.read()) != -1) {
        out.write(b);
    }
    out.flush();
    //4 删除多余文件
    ZipHelper.deleteDir(new File(path));
    in.close();//先关闭输入流才能删除
    ZipHelper.deleteDir(new File(zipFileName));
    out.close();

    } catch (Exception e) {
        R.failed("下载二维码错误"+e);
        e.printStackTrace();
    }
    return null;
}