验证码图片保存到本地

    @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;
    }

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值