干货直接上代码-------本文讲解
本文是通过前端访问后台的接口传递一个 id 参数 后台根据该参数生成二维码并且以流的形式输出到前端进行下载
/**
* 暴露的接口--下载二维码
*
* @param response
* @throws IOException
*/
@GetMapping("/download/{id}")
@ApiOperation("二维码下载")
public void downloadCode(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws IOException {
try {
Course course = courseService.getById(id);
//二维码中包含的信息
String content = "courseId:" + course.getId();
//生成二维码流
BitMatrix bitMatrix = createQrcode(content,300,400);
//设置请求头
response.setContentType("application/octet-stream");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(course.getName()+".png", "utf-8"));
OutputStream outputStream = response.getOutputStream();
MatrixToImageWriter.writeToStream(bitMatrix, "png", outputStream);
outputStream.flush();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 生成二维码流
* @param content 二维码内容
* @param width 二维码宽度
* @param height 二维码高度
* @return
* @throws WriterException
*/
public static BitMatrix createQrcode(String content,int width,int height)throws WriterException{
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, width, height, hints);
return bitMatrix;
}