最近有个需求是要实现下载文档,但是后端返回需要下载的文档个数又不能做限制,所以最初想要用a标签简单的实现下载就不能生效了,因为会默认下载多个下载链接的最后一个,后面换了个办法用blob对象实现
直接上代码
单个下载:
用a标签实现,调用download属性,具体自己去百度..
批量下载:
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();
});
},
async download(url, filename) {
const res = await this.getBlob(url);
const downUrl = res ? URL.createObjectURL(res) : "javascript:void(0);";
// 创建隐藏的可下载链接
let eleLink = document.createElement("a");
eleLink.style.display = "none";
eleLink.download = filename;
// 兼容:某些浏览器不支持HTML5的download属性
if (typeof eleLink.download === "undefined") {
eleLink.setAttribute("target", "_blank");
}
eleLink.href = downUrl;
// 触发点击
document.body.appendChild(eleLink);
eleLink.click();
// 然后移除
setTimeout(() => {
document.body.removeChild(eleLink);
}, 20);
},