blob是浏览器提供用来处理二进制的一个对象,我们用form来上传文件的时候,所使用的input,将它的类型设置为file,用户选择文件之后,会返回一个FileList对象,File对象就在FileList对象当中,File对象继承自blob,这能让我们获取更多的文件信息。说了这么多来看一下如何创建一个blob对象。在blob还未被规范的时候,是使用blobBuilder来创建一个blob对象,而现在我们可以直接调用blob的构造函数来创建一个blob对象。
先来看一下blob的构造函数
Blob(array,options)
从这里可以看出blob构造函数接受两个参数,第一个参数为一个数组,为需要被处理的数据,第二个参数为配置参数,一般填上该数据的mime类型。
比如我现在创建一个blob实例,设置它的mime类型为text/html。把数据装载进blob对象有一个好处就是可以使用URL.createObjectURL来返回一个url来进行引用,比如我现在把这个blob对象转换为了url,把它交给iframe的src,现在来看一下效果
let blob = new Blob([`
<h1>Hello, i'm a Blob</h1>
`],{type:"text/html"});
下面是项目中使用axios请求的代码,
$({
methods: 'get',
url: `......`,
responseType: 'blob'
}).then(res => {
let fileName = decodeURI(
res.headers['content-disposition'].split(`filename*=UTF-8''`)[1] /此处根据实际返回下载文件名称分割
);
let blob = new Blob([res.data], {
type: res.headers['content-type'] //根据返回文件类型
});
if (window.navigator.msSaveOrOpenBlob) {
navigator.msSaveBlob(blob, fileName);
} else {
// 非IE下载
const elink = document.createElement('a');
elink.style.display = 'none';
elink.href = URL.createObjectURL(blob);
elink.download = fileName;
document.body.appendChild(elink);
elink.click();
setTimeout(() => {
URL.revokeObjectURL(elink.href); // 释放URL 对象
document.body.removeChild(elink);
}, 5000); //解决部分浏览器下载时“无此文件”问题
}
})
.catch(function(error) {
console.log(error);
});