js通过文件路径下载文件,而页面不发生跳转
一、js下载文件而页面不进行跳转
1)方法一:
通过a标签触发文件流形式,代码如下:
let url = 'http://xxxxx.zip'
fetch(url)
.then(res => res.blob())
.then(blob => {
const a = document.createElement("a");
const objectUrl = window.URL.createObjectURL(blob);
a.download = '文件.zip';
a.href = objectUrl;
a.click();
window.URL.revokeObjectURL(objectUrl);
a.remove();
})
2)方法二:
通过iframe方式进行下载:
const iframe = document.createElement("iframe");
iframe.setAttribute("hidden","hidden");
document.body.appendChild(iframe);
iframe.onload = () => {
if(iframe){
iframe.setAttribute('src','about:blank');
}
};
let url = 'http://xxx.zip'
iframe.setAttribute("src",url);