背景
在以前,历来都是后端返一个图片地址,而后前端直接使用。 那若是后端返了一个图片文件过来,那要怎么作?javascript
参考:css
vue axios请求图片流文件前端页面显示处理方法html
正文
此次我接收到的直接是一个图片文件,而后乱码了。。 以下图java
要怎么处理呢?ios
首先是第一步,请求处理,下面我分别列出了axios、fetch、jq、原生js的处理方式web
1.修改请求
1.1. axios
重点在于添加option: responseType: 'arraybuffer'
ajax
let url = `imgurl`;
axios.get(url,{responseType: 'arraybuffer'}).then(function(data){
console.log(data);
}).catch(function(err){
error(err)
});
复制代码
1.2. fetch
咱们在使用fetch的时候,会有一个response的对象处理过程。 广泛咱们都是使用的 response.json()
,但此次咱们须要进行response.arrayBuffer()
处理json
fetch(url)
.then(function(response) {
if(response.ok) {
return response.arrayBuffer(); // 这一行是关键
}
throw new Error('Network response was not ok.');
})
.then(function(data) {
console.log(data)
})
.catch(function(error) {
});
复制代码
1.3. JQ-ajax
若是使用jq封装的ajax,那么抱歉,这个功能用不了。
jq封装的ajax是基于xhr初版本的,而ArrayBuffer是基于xhr第二版本的
这种状况就推荐使用原生js来写
1.4. 原生js
let xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'arraybuffer'; // 重点
let that = this; // 这个不是必须,只是用来保存this的指向
xhr.onload = function(e) {
if (this.status == 200) {
let result = this.response;
console.log(result)
}
};
xhr.send();
复制代码
补充知识点
responseType设置的是啥? arraybuffer又是啥?
这些内容估计又能够开一篇文章来写了,详细的能够参考如下网址:
MDN-XMLHttpRequest.responseType
2.处理返回值
好了,咱们如今已经获取到了咱们须要的二进制数组(arrayBuffer) 下一步,咱们要把图片显示处理,使用base64编码便可
let imgUrl = 'data:image/png;base64,' + btoa(new Uint8Array(data.data).reduce((data, byte) => data + String.fromCharCode(byte), ''))
// 这里若是不清楚 new Uint8Array(data.data) 中data的指代,就看看最上面的那个图
复制代码
这样能将图片进行编码,而后作前端缓存(若是用localStorage缓存blob,存能成功,可是刷新后再取出来是看不见图片的)。
解释一下各自含义:
data: ----获取数据类型名称
image/png; -----指数据类型名称
base64 -----指编码模式
AAAAA ------指编码之后的结果。
3.使用
2种方法:
- 若是使用vue这类框架,能够直接style赋值
- 建立动态style,建立动态css
第一个这个使用就不说了,直接src=imgUrl
;
//vue
<img :src="imgUrl">
复制代码
第二个咱们要作的就是建立style节点,并添加在head种
if(document.all){ // document.createStyleSheet(url)
window.style=`.imga{background-img: url(${imgUrl});`;
document.createStyleSheet("javascript:style");
}else{ //document.createElement(style)
var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML=`.imga{background-img: url(${imgUrl});`;
document.getElementsByTagName('HEAD').item(0).appendChild(style);
}
复制代码
这样,就动态建立了相应的style样式。 而后给须要的地方添加上 .img 便可
...
<div class="imga">
...
</div ... 复制代码