@RequestMapping("/captcha")
@ApiOperation(value = "生成验证码信息", produces = "application/octet-stream")
public ResponseResult generateCaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException, FontFormatException {
// 3个设置都是为了不缓存响应数据,同时设置可以兼容不同的浏览器或缓存服务器
response.setHeader("Cache-Control", "no-store");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
// 响应内容是一个PNG格式的图像
response.setContentType("image/png");
// 生成不同类型验证码,三个参数分别为宽、高、位数
// png类型
// SpecCaptcha captcha = new SpecCaptcha(180, 40, 4);
// gif类型
// GifCaptcha captcha = new GifCaptcha(180, 40, 4);
// 中文类型
// ChineseCaptcha captcha = new ChineseCaptcha(180, 40, 4);
// 中文gif类型
// ChineseGifCaptcha captcha = new ChineseGifCaptcha(180, 40, 4);
// 算术类型
ArithmeticCaptcha captcha = new ArithmeticCaptcha(180, 40, 4);
// 设置字符类型
captcha.setCharType(Captcha.TYPE_DEFAULT);
// 设置字体
// captcha.setFont(Captcha.FONT_8, 40);
// 将图片存到upload
// 获取resources目录路径
String resourcesPath = new File(ClassLoader.getSystemResource("").getPath()).getAbsolutePath();
// 定义upload目录路径
String uploadDirPath = resourcesPath + File.separator + "upload";
// 创建upload目录(如果不存在)
File uploadDir = new File(uploadDirPath);
if (!uploadDir.exists()) {
uploadDir.mkdirs();
}
// 定义文件路径
String fileName = UUID.randomUUID() + "captcha.png"; // 可以根据需要动态生成文件名
File file = new File(uploadDirPath + File.separator + fileName);
// 保存验证码图片到本地文件
try (FileOutputStream fos = new FileOutputStream(file)) {
captcha.out(fos);
}
ResponseResult result = ResponseResult.okResult();
result.setData("localhost:8080/upload/" + fileName);
return result;
}
验证码图片保存到本地
最新推荐文章于 2024-10-01 18:51:18 发布