Vue后端返回图片,前端显示
目录
Vue后端返回图片,前端显示
Vue后端返回图片,前端显示
首先我们明确两个点:
- 普通请求接收的时候是json格式,图片流的接收模式可选两种:blob和arraybuffer。
- blob和arraybuffer本质上都是二进制数据。
- 如果使用blob我们只需要用
window.URL.createObjectURL(res)
就可以得到图片链接; - 如果使用arraybuffer,我们需要将其转为base64的格式。
- 如果使用blob我们只需要用
<div class="getCaptcha" @click="getimgCaptcha()">
<img
:src="codeImg"
style="width:135px;height:40px;"
alt="点击重新获取验证码"
>
</div>
1. blob
请求设置,代码如下:
export function getCaptcha () {
return request({
url: /getCaptcha,
method: 'get',
responseType: 'blob' //选择接收方式为blob
})
}
图片处理,代码如下:
getCaptcha (e) {
getCaptcha().then(res => {
this.codeImg = window.URL.createObjectURL(res) // 这里调用window的URL方法
console.log(this.codeImg, '地址')
})
.catch(err => {
console.log(err)
})
},
2. arraybuffer
请求设置,代码如下:
// 图片验证码
export function getCaptcha () {
return request({
url: /getCaptch,
method: 'get',
responseType: 'arraybuffer'
})
}
图片处理,代码如下:
getCaptcha (e) {
getCaptcha().then(res => {
//1. btoa表示 base64转ASCII ,对应的还有 atob 表示 ASCII转base64
//2. Unit8Arrat() 是arraybuffer里面的一种类型
const url = 'data:image/png;base64,' + btoa(new Uint8Array(res).reduce((data, byte) => data + String.fromCharCode(byte), ''))
this.codeImg = url
console.log(this.codeImg, '地址')
})
.catch(err => {
console.log(err)
})
},