vue中后端返回图片流,前端渲染方法

前端登录经常用到图形验证码,后端接口返回的是图片数据流,如下图返回图片流这样
在这里插入图片描述
效果图如下:
在这里插入图片描述

首先封装接口api和uuid[就是一个随机数,防止重复]

//获取图形验证码接口/auth/system/captcha.jpg
export function getCaptcha(query) {
  return request({
    url: "auth/system/captcha.jpg",
    params: query,
    method: "get",
    responseType:"blob" //这个非常重要,配置blob类型【第一个方法必须配置,第二个不用配置】
  });
}
/**
 * 获取uuid
 */
 export function getUUID() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
    return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
  })
}

第一种方法

导入封装好的api

<img ref="vcImg" :src="codeUrl" @click="getCaptchaImg()" alt style="width: 100px;height: 49px;"/>
import { getCaptcha,getUUID } from '@/api/login'
export default{
	data(){
		return{
			codeUrl: "",
        	captchaUUid:'',
		}
	},
	methods:{
		 // 获取图形验证码
		 getCaptchaImg() {
		    this.captchaUUid = getUUID()
		    var params = {
		      uuid: this.captchaUUid
		    }
		    getCaptcha(params).then((res)=>{
		      this.codeUrl = window.URL.createObjectURL(res) //获取图片流的路径
		    })
		  },
	}
}

第二种方法

 <img ref="vcImg" src="auth/system/captcha.jpg" @click="getCaptchaImg()" alt style="width: 100px;height: 49px;"/>
 import { getCaptcha,getUUID } from '@/api/login'
export default{
	data(){
		return{
			codeUrl: "",
        	captchaUUid:'',
		}
	},
	methods:{
		 // 获取图形验证码
      getCaptchaImg() {
        this.captchaUUid = getUUID()
        var params = {
          uuid: this.captchaUUid
        }
        getCaptcha(params).then((res)=>{
          //地址拼接uuid,重新获取一下src地址,这个方法地址若是修改的话,需要和配置地址一起修改,没用第一个方法方便
          this.$refs.vcImg.src = 'http://xxxxx/auth/system/captcha.jpg?uuid=' + this.captchaUUid
        })
    },
	}
}
 
Logo

基于 Vue 的企业级 UI 组件库和中后台系统解决方案,为数万开发者服务。

更多推荐