a标签
let a = document.createElement("a"), //创建a标签 e = document.createEvent("MouseEvents"); //创建鼠标事件对象 e.initEvent("click", false, false); //初始化事件对象 a.href = href; //设置下载地址 a.download = name; //设置下载文件名 a.rowKey = name; //设置下载文件名 a.dispatchEvent(e); //给指定的元素,执行事件click事件
a标签仅可以实现单文件下载,多次点击会出现请求竟然自动Cancelled了
iframe
iframe也可以向服务器发请求的,代码贴出来。
export const downloadFile = (url) => {
const iframe = document.createElement("iframe");
iframe.style.display = "none"; // 防止影响页面
iframe.style.height = 0; // 防止影响页面
iframe.src = url;
document.body.appendChild(iframe); // 这一行必须,iframe挂在到dom树上才会发请求
// 5分钟之后删除(onload方法对于下载链接不起作用,就先抠脚一下吧)
setTimeout(()=>{
iframe.remove();
}, 5 * 60 * 1000);
}
ps: iframe不会相互影响,可以连续下载哦!