记录一下最近遇到的一个需求,点击下载按钮,获取到了文件的url地址,然后进行下载,在网上找了好多相关资料才搞出来,这里用到了我的知识大盲区new XMLHttpRequest(),必须记录一下,之前没有用blob单纯用a标签其实也可以完成这个需求,但是不能修改文件名,下载时的文件名是一串乱七八糟的码,而且响应的速度也很慢,用下面这个方法虽然陌生,但是超好用!!
upload(url,name) {
this.getBlob(url).then(blob => {
let a = document.createElement('a');
let url = window.URL.createObjectURL(blob);
a.setAttribute('href', url);//文件下载地址
a.setAttribute('target', '_blank');
a.setAttribute('download', name);//修改文件名
document.body.appendChild(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
})
},
getBlob(url) {
return new Promise(resolve => {
const xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'blob';
xhr.onload = () => {
if (xhr.status === 200) {
resolve(xhr.response);
}
};
xhr.send();
});
},