How do you automatically download a file in javascript?

故事扮演 提交于 2020-01-14 17:55:10

问题


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. 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!


回答1:


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.

<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?)




回答2:


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();


来源:https://stackoverflow.com/questions/36903527/how-do-you-automatically-download-a-file-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!