![](/img/trans.png)
[英]How do you serve a file for download with AngularJS or Javascript?
[英]How do you automatically download a file in javascript?
所以,我一直在尋找並試圖找到一種方法,當有人訪問我的網站時自動下載文件。 我試過使用 a 標簽進行下載,它可以工作,您只需單擊即可下載它。 像這樣...
<a href="pic.jpg" download>Download</a>
但我不想那樣。 我希望它無需單擊即可自動下載。 我需要一些幫助,請!
如果它是一個實際文件(不會像 JPG 文件那樣簡單地顯示在您的瀏覽器中),那么您可以使用 javascript 或元重定向。
<script> document.location.href = 'yourfile.exe'; </script>
或
<meta http-equiv="refresh" content="0; url=yourfile.exe">
但我想知道您是否在談論用戶被詢問是否要打開或保存文件(無論是 JPG 還是其他文件?)
另一種方法:
var a = document.createElement('a');
a.setAttribute('href', dataUri);
a.setAttribute('download', filename);
var aj = $(a);
aj.appendTo('body');
aj[0].click();
aj.remove();
另一個純 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);
}
然后你可以在加載時調用函數:
downloadFile(/*pass your file here*/);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.