Java生成二维码并通过浏览器下载

在这里只放controller
1.需要的依赖

<!--谷歌 生成二维码使用-->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.3.3</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.3.3</version>
        </dependency>

2.Controller方法
请网友使用
@GetMapping(“/test”)

public void qRode(HttpServletRequest request,HttpServletResponse response) throws IOException, WriterException {}
其他内容根据自己需求调整,这里只为记录,方便以后使用

@GetMapping("/test/{id}")
    public void qRode(@PathVariable("id") Long id,HttpServletRequest request,HttpServletResponse response) throws IOException, WriterException {
        //二维码中包含的信息
        String content = "hello";
        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, 500, 500, hints);
        // 二维码名称
        String fileName = "下载的二维码名称.png";
        String userAgent=request.getHeader("User-Agent");
        if (userAgent.contains("MSIE") || userAgent.contains("Trident") || userAgent.contains("Edge")) {//IE
            fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
        } else {
            fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");// 谷歌/火狐
        }
        //设置请求头
        response.setHeader("Content-Type","application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName );
        OutputStream outputStream = response.getOutputStream();
        MatrixToImageWriter.writeToStream(bitMatrix, "png", outputStream);
        outputStream.flush();
        outputStream.close();
    }

你可能感兴趣的:(JavaWeb开发进行时,java,servlet,开发语言)