zoukankan      html  css  js  c++  java
  • java后台生成并下载二维码

    这个功能在项目开发中是很基础的,平时用到的也很多,这里简单记录一下,以便以后使用的时候参考

    前提业务要求:前台页面展示数据,有下载按钮点击下载,下载对应数据的二维码。

    首先,在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 = "姓名:十二余
    博客: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


  • 相关阅读:
    Javascript操作cookie
    上传文件-layui+ashx
    Mysql对查询结果添加序列号
    Maven详解
    解决 go iris ReadJSON 无法获取 json,并提示 unexpected end of JSON input 的错误
    Archlinux 最新安装方法 (2020.07.01-x86_64)之虚拟机 BIOS 安装
    Oracle APEX 发送邮件
    包管理Go module的使用
    Golang 解决 Iris 被墙的依赖包
    解决 Nginx 代理Apex慢的问题
  • 原文地址:https://www.cnblogs.com/jing5464/p/9951198.html
Copyright © 2011-2022 走看看