字节数组与图片
小于 1 分钟javascript
概述
前端请求后端验证码图片时可以结束类型 arraybuffer 的数据然后转换为图片显示到前端页面,多用于验证码功能上
实现
初次实现在 electron 项目登录页面获取验证码的功能,http 请求代码如下,在请求属性 responseType 中显示指定了响应来的数据类型
import req from '@utils/request'
// 传入 uuid 获取图形验证码
const getCaptchaImg = uuid => {
return req({
url: '/captcha/image',
params: {key: uuid},
responseType: 'arraybuffer'
})
}
export { getCaptchaImg }
js 中接受该数据的案例
let captchUrl = ref('')
const initCaptchImg = async () => {
const uuid = new Date().getTime().toString()
const arrBuffer = await getCaptchaImg(uuid)// 传入时间戳作为参数请求验证码图片
const blob = new Blob([arrBuffer],{type:'application/vnd.ms-excel'})// 将字节数组转换为 blob 对象
captchUrl.value = URL.createObjectURL(blob)// 将 blob 对象转换为图片 url
}
// html 中显示图片
<el-image :src="captchUrl">验证码图片</el-image>
