生成验证码为11111的base64图片编码

1、Login.vue

<template>
  <el-row type="flex" class="row-bg" justify="center">
    <el-col :span="12" :xl="6" :lg="7">
      <div class="login-form">
        <h2>欢迎来到Hangtime管理系统</h2>
        <el-image
          style="width: 180px; height: 90px"
          :src="require('@/assets/img/logo.png')"
        ></el-image>
        <p>欢迎!</p>
        <p>管理员</p>
      </div>
    </el-col>
    <el-col :span="1">
      <el-divider direction="vertical" />
    </el-col>
    <el-col :span="11" :xl="6" :lg="7">
      <el-form
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <h3>请输入</h3>
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password" />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="ruleForm.code" />
          <el-image class="captchaImg" :src="loginForm.captchaImg"></el-image>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" style="width: 172px; float: left;" @click="submitForm(ruleFormRef)">
            提交
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<script setup lang="ts">
import { reactive, ref } from 'vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import axios from 'axios'

interface RuleForm {
  username: string
  password: string
  code: string
}

interface LoginForm {
  token: string
  captchaImg: string
}

const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  username: '',
  password: '',
  code: ''
})

const loginForm = reactive<LoginForm>({
  token: '',
  captchaImg: ''
})

const rules = reactive<FormRules<RuleForm>>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
  ],
  code: [
    { required: true, message: '请输入验证码', trigger: 'blur' },
    { min: 5, max: 5, message: '长度为5个字符', trigger: 'blur' },
  ]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        const res = await axios.post('/login', loginForm);
        console.log(res.data); // 输出服务器返回的数据
      } catch (error) {
        console.error('登录失败:', error);
      }
    } else {
      console.log('表单验证未通过:', fields);
    }
  });
};

const getCaptcha = () => {
  axios.get('/captcha')
    .then(res => {
      console.log(res);
      loginForm.token = res.data.data.token;
      loginForm.captchaImg = res.data.data.captchaImg;
    }).catch(error => {
      console.error('获取验证码失败:', error);
    });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}));

// 在这里调用获取验证码的方法
getCaptcha();

</script>

<style scoped>
.el-col {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;
  text-align: center;
}
.el-row {
  height: 660px;
  background-color: #fafafa;
}
.el-divider {
  height: 200px;
}
</style>



2、mock.js

// 引入mockjs
import Mock from 'mockjs';

const Random = Mock.Random
//模拟后端进行数据的封装
let Result = {
   code: 200,
   msg: '操作成功',
   data: null
}
// 获取验证码图片base64编码以及一个随机码
Mock.mock('/captcha', 'get', () => {
   Result.data = {
      token: Random.string(32), // 获取一个32位的随机字符串,
      captchaImg: Random.dataImage( "120x40", "11111" ) //生成验证码为11111的base64图片编码
   }
   return Result
})

显示结果
请添加图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
可以使用Java的Base64编码器将验证码转换为Base64编码的字符串,然后将其作为JSON响应发送到前端。在前端,可以使用JavaScript的atob()函数将Base64编码的字符串解码,并将其显示在图像元素中。 以下是一个示例代码片段,用于将Java中生成验证码编码Base64字符串并将其发送到前端: ```java @RestController public class CaptchaController { @Autowired private CaptchaService captchaService; @PostMapping("/captcha") public ResponseEntity<Map<String, String>> generateCaptcha() { BufferedImage image = captchaService.generateCaptcha(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { ImageIO.write(image, "png", baos); } catch (IOException e) { e.printStackTrace(); } byte[] bytes = baos.toByteArray(); String base64 = Base64.getEncoder().encodeToString(bytes); Map<String, String> response = new HashMap<>(); response.put("captcha", base64); return ResponseEntity.ok(response); } } ``` 在前端,可以使用以下代码将Base64编码的字符串解码并将其显示在图像元素中: ```javascript fetch('/captcha', { method: 'POST' }) .then(response => response.json()) .then(data => { const captchaImg = document.createElement('img'); captchaImg.src = 'data:image/png;base64,' + data.captcha; document.body.appendChild(captchaImg); }); ``` 在这个示例中,我们从后端获取Base64编码验证码,并将其设置为图像元素的源。由于图像元素需要一个URL作为源,我们需要使用"data" URL格式,并在Base64编码的字符串之前添加"data:image/png;base64,"前缀。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Yuexin️

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值