[英]How do you automatically download a file in javascript?
So, I've been looking and trying to find a way to download a file automatically right when somebody goes onto my site.所以,我一直在寻找并试图找到一种方法,当有人访问我的网站时自动下载文件。 I've tried using an a tag to download, and it works, you just have to click to download it.我试过使用 a 标签进行下载,它可以工作,您只需单击即可下载它。 Like so...像这样...
<a href="pic.jpg" download>Download</a>
But I don't want that.但我不想那样。 I want it to automatically download with no click.我希望它无需单击即可自动下载。 I need some help please!我需要一些帮助,请!
If it's an actual file (something that won't simply display in your browser like a JPG file) then you could use a javascript or meta redirect.如果它是一个实际文件(不会像 JPG 文件那样简单地显示在您的浏览器中),那么您可以使用 javascript 或元重定向。
<script> document.location.href = 'yourfile.exe'; </script>
or或
<meta http-equiv="refresh" content="0; url=yourfile.exe">
But I am wondering if you might be talking about the user being asked if they want to open or save a file (whether it's a JPG or whatever?)但我想知道您是否在谈论用户被询问是否要打开或保存文件(无论是 JPG 还是其他文件?)
Another way to do it :另一种方法:
var a = document.createElement('a');
a.setAttribute('href', dataUri);
a.setAttribute('download', filename);
var aj = $(a);
aj.appendTo('body');
aj[0].click();
aj.remove();
Another option which is pure javascript is:另一个纯 javascript 选项是:
const downloadFile = (file) => {
const element = document.createElement('a');
element.setAttribute('href', 'Download Btn');
element.setAttribute('download', file);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
And then you can call the function on load:然后你可以在加载时调用函数:
downloadFile(/*pass your file here*/);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.