一般我们实现下载功能时,很多时候都是通过后端返回的链接从服务器上把文件下载到本地,但当后端返回给我们的是一个Blob文件流时,我们应该怎么做?
(1) axios方式(推荐)
axios({
method:'get',
url:url,
responseType:'blob' //定义接收类型
})
.then((res) => {
if(res.success && res.result){
this.downFile(res.result.data, res.result.fileName); //下载文件
}
});
downFile = (data, name) => {
if(!data){
alert('数据错误!');
return;
}
let BLOB = new Blob([data]);
let url = window.URL.createObjectURL(BLOB);
let link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.setAttribute('download', name);
document.body.appendChild(link);
link.click();
}
(2) 原生Ajax
function (ajaxUrl, name){
let xhr = new XMLHttpRequest();
xhr.open('GET', ajaxUrl, true);
xhr.responseType = 'blob'; //返回类型blob
//定义请求完成的处理函数,请求前也可以增加加载框/禁用下载按钮逻辑
xhr.onload = function (res){
//请求完成
if(this.status === 200){
//返回200
if(this.response.size > 0){ //获取到了数据
let data = this.response;
if(!data){
alert('数据错误!');
return;
}
let BLOB = new Blob([data]);
let url = window.URL.createObjectURL(BLOB);
let link = document.createElement('a');
link.style.display = 'none';
link.href = url;
link.setAttribute('download', name);
document.body.appendChild(link);
link.click();
}else{
alert('未返回数据!');
}
}
}
}
(3) Ajax.get()
可能会有朋友想要用Ajax.get()方法,但是有一个致命的缺陷是,它并不支持‘blob’数据流方式。具体请参考W3C文档:jQuery ajax - get() 方法
微信扫码加入「老爹古董店」,回复“Blob”,一起游戏人生!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。