使用vue指令加载需要权限验证的图片

1,404 阅读1分钟

背景:你一定遇到过接口需要加请求头字段验证权限吧,当有一天,请求图片也要通过后端网关,需要验证权限的时候,客官且看!

1. 请求图片增加请求头验证信息

// 此处的service为你封装过的axios(即添加过请求头认证信息的)
import {service} from '@/api'
// 此处res.data即为请求得到的二进制图片数据流
service.get(url, {responseType: 'blob'}).then(res => {})

你现在拿到了图片的二进制流

2. 处理二进制流

URL.createObject()方法会根据传入参数创建一个指向该参数的URL,这个URL的生命仅存在于被创建的这个文档里面。也就是说,这个对象URL指向file或者blob对象

objectURL = URL.createObjectURL(blob || file)

当你已经用过这个URL对象的时候,要让浏览器知道这个URL不再指向对应的文件,需要调用方法解绑

img.src = objectURL
img.onload = () => {
    window.URL.revokeObjectURL(objectURL)
}

3. 创建指令

function setImgSrc (el, {value, oldValue}) {
    // 如果没有src 或者src没替换
    if (!value || value === oldValue) return
    let url = value.trim()
    // 是否设置为背景图的 flag
    let setAsBg = false
    if (value.startsWith('url(')) {
        setAsBg = true
        url = value.slice(4, -1)
    }
    service.get(url, {
        responseType: 'blob'
    }).then(res => {
        let blobUrl = URL.createObjectURL(res.data)
        if (setAsBg) {
            el.style.backgroundImage = `url(${blobUrl})`
        } else {
            el.src = blobUrl
            el.onload = () => {
                console.log(blobUrl, '1')
                window.URL.revokeObjectURL(blobUrl)
                console.log(blobUrl, '2')
            }
        }
    })
}
export default {
    bind (el, binding) {
        setImgSrc(el, binding)
    },
    componentUpdated (el, binding) {
        setImgSrc(el, binding)
    }
}

使用

<img v-auth-img="http://www.baidu.com/***">
import authImg from '@/directives/auth-img'
export default {
    directives: {authImg}
}

最后,有错误还望指出交流~