新增二维码生成接口
This commit is contained in:
@@ -0,0 +1,69 @@
|
||||
package com.gxwebsoft.common.core.controller;
|
||||
|
||||
import cn.hutool.extra.qrcode.QrCodeUtil;
|
||||
import cn.hutool.extra.qrcode.QrConfig;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import com.gxwebsoft.common.core.web.BaseController;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.awt.*;
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* 二维码生成控制器
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2025-08-18
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api")
|
||||
@Tag(name = "二维码生成API")
|
||||
public class QrCodeController extends BaseController {
|
||||
|
||||
@Operation(summary = "生成二维码")
|
||||
@GetMapping("/create-qr-code")
|
||||
public void createQrCode(
|
||||
@RequestParam("data") String data,
|
||||
@RequestParam(value = "size", defaultValue = "200x200") String size,
|
||||
HttpServletResponse response) throws IOException {
|
||||
|
||||
try {
|
||||
// 解析尺寸
|
||||
String[] dimensions = size.split("x");
|
||||
int width = Integer.parseInt(dimensions[0]);
|
||||
int height = dimensions.length > 1 ? Integer.parseInt(dimensions[1]) : width;
|
||||
|
||||
// 验证尺寸范围,防止过大的图片
|
||||
if (width < 50 || width > 1000 || height < 50 || height > 1000) {
|
||||
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
|
||||
response.getWriter().write("尺寸必须在50-1000像素之间");
|
||||
return;
|
||||
}
|
||||
|
||||
// 配置二维码
|
||||
QrConfig config = new QrConfig(width, height);
|
||||
config.setMargin(1);
|
||||
config.setForeColor(Color.BLACK);
|
||||
config.setBackColor(Color.WHITE);
|
||||
|
||||
// 设置响应头
|
||||
response.setContentType("image/png");
|
||||
response.setHeader("Cache-Control", "no-cache");
|
||||
response.setHeader("Content-Disposition", "inline; filename=qrcode.png");
|
||||
|
||||
// 生成二维码并直接输出到响应流
|
||||
QrCodeUtil.generate(data, config, "png", response.getOutputStream());
|
||||
|
||||
} catch (NumberFormatException e) {
|
||||
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
|
||||
response.getWriter().write("尺寸格式错误,请使用如:200x200 的格式");
|
||||
} catch (Exception e) {
|
||||
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
|
||||
response.getWriter().write("生成二维码失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -76,7 +76,8 @@ public class SecurityConfig {
|
||||
"/api/hjm/hjm-car/**",
|
||||
"/api/chat/**",
|
||||
"/api/shop/getShopInfo",
|
||||
"/api/shop/shop-order/test"
|
||||
"/api/shop/shop-order/test",
|
||||
"/api/create-qr-code"
|
||||
)
|
||||
.permitAll()
|
||||
.anyRequest()
|
||||
|
||||
Reference in New Issue
Block a user