Java 生成可直接下载的二维码(spring boot)

论坛 期权论坛 脚本     
匿名技术用户   2020-12-21 15:33   17   0

最近做的一个项目中,需要提供给web端一个接口:downloadQr。用到了Google的Zxing框架。项目使用的是springboot框架。

一、API文档

接口名称:/downloadQr
接口描述:生成可直接下载的二维码图片
请求方式:GET
请求参数:String data
响应内容:二维码图片数据流

二、下面直接上代码

  • controller层
import com.google.zxing.WriterException;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@GetMapping("downloadQr")
public void downloadQr(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, 
String data) throws IOException, WriterException {
    globalBiz.downloadQr(httpServletRequest, httpServletResponse, data);
}
  • biz层 interface
import com.google.zxing.WriterException;
import org.springframework.web.bind.annotation.GetMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

void downloadQr(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String data) throws WriterException, IOException;
  • biz层 实现
import com.google.common.collect.Lists;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;

其中关键常量:
CharsetConstant.UTF_8 = "UTF_8";
Constant.QR_WIDTH = 300;
QR_FILE_TYPE = "png";

@Override
    public void downloadQr(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, String data) throws WriterException, IOException {
        String dataHandle = new String(data.getBytes(CharsetConstant.UTF_8), CharsetConstant.UTF_8);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(dataHandle, BarcodeFormat.QR_CODE, Constant.QR_WIDTH, Constant.QR_HEIGHT);

        httpServletResponse.reset();//清空输出流

        OutputStream os = httpServletResponse.getOutputStream();//取得输出流
        MatrixToImageWriter.writeToStream(bitMatrix, QR_FILE_TYPE, os);//写入文件刷新

        os.flush();
        os.close();//关闭输出流
    }
分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP