方法一
// 发送请求并接收文件流
axios.get('url', {
responseType: 'blob' // 指定响应类型为文件流
}).then((response) => {
const blob = new Blob([response.data], { type: response.data.type }); // 保存文件流为 Blob
const imageUrl = URL.createObjectURL(blob); // 转换 Blob 为 URL
// 显示图片
const img = document.createElement('img');
img.src = imageUrl;
document.body.appendChild(img);
}).catch((error) => {
console.log(error);
});
在上面的代码中,我们可以看到.get请求通过responseType: 'blob’指定响应类型为文件流。然后,我们将响应中的数据转换为Blob对象,并通过URL.createObjectURL方法将它转换为URL。最后,我们创建一个img元素,并将URL作为src属性值,从而将图片展示在页面中。
方法二
// 发送请求并接收文件流
axios.get('url', {
responseType: 'blob' // 指定响应类型为文件流
}).then((response) => {
var reader = new FileReader();
reader.readAsDataURL(response.data)
reader.onloadend = function() {
// 显示图片
const img = document.createElement('img');
img.src = reader.result;
document.body.appendChild(img);
}
}).catch((error) => {
console.log(error);
});
这里两种方法都是可以,大家随意选取其中一种即可(本来博主用的第二种方法,但是发现第一种写的代码更少,就更换并且记录下来了)