let xhr = new XMLHttpRequest() xhr.open('get', imgUrl='www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png', true) xhr.responseType = 'blob' xhr.onload = function () { if (this.status === 200) { let blob = this.response let fileReader = new FileReader() fileReader.onloadend = function (e) { // el.src = e.target.result } fileReader.readAsDataURL(blob) } } xhr.send()
解决vue项目绑定img src但 ie不显示 于是写成自定义指令
Vue.directive('toBase64', { bind: function (el, binding) { const { value: imgIds } = binding let showImg = '' let defaultImg = '' if (Array.isArray(imgIds)) { showImg = imgIds[0] defaultImg = imgIds[1] } else { showImg = imgIds } let imgUrl = config.imgBaseUrl + showImg if (!showImg || !window.navigator.msSaveBlob) { el.src = showImg ? imgUrl : defaultImg return } let xhr = new XMLHttpRequest() xhr.open('get', imgUrl, true) xhr.responseType = 'blob' xhr.onload = function () { if (this.status === 200) { let blob = this.response let fileReader = new FileReader() fileReader.onloadend = function (e) { el.src = e.target.result } fileReader.readAsDataURL(blob) } } xhr.send() }, update: function (el, binding) { const { oldValue, value: imgIds } = binding if (oldValue.toString() === imgIds.toString()) { return } let showImg = '' let defaultImg = '' if (Array.isArray(imgIds)) { showImg = imgIds[0] defaultImg = imgIds[1] } else { showImg = imgIds } let imgUrl = config.imgBaseUrl + showImg if (!showImg || !window.navigator.msSaveBlob) { el.src = showImg ? imgUrl : defaultImg return } let xhr = new XMLHttpRequest() xhr.open('get', imgUrl, true) xhr.responseType = 'blob' xhr.onload = function () { if (this.status === 200) { let blob = this.response let fileReader = new FileReader() fileReader.onloadend = function (e) { el.src = e.target.result } fileReader.readAsDataURL(blob) } } xhr.send() } })