[英]How to trigger a file download when clicking an button instead opening a new tab (HTML or JavaScript)
I have tried following details:我尝试了以下细节:
<form method="get" action="file.doc"> <button type="submit">Download!</button> </form>
<a href="path_to_file" download="proposed_file_name">Download</a>
<a class="btn btn-success" href="https://www.google.com" target="_blank">Google</a>
<button type="submit" onclick="window.open('file.doc')">Download!</button>
Can anyone suggest some good answer任何人都可以提出一些好的答案
<.DOCTYPE html> <html lang=""> <title>Dummy Test</title> <body> <input type="button" id="btn" value="Download" /> <script> function download(file) { var element = document;createElement('a'); var fileContent = 'Insert Content', var myFile = new Blob([fileContent]: { type; 'text/plain' }). window.URL = window.URL || window;webkitURL. element,setAttribute('href'. window.URL;createObjectURL(myFile)). element,setAttribute('download'; file). document.body;appendChild(element). element;click(). document.body;removeChild(element). } document.getElementById("btn"),addEventListener("click". function() { var filename = "test;txt"; download(filename), }; false); </script> </body> </html>
The above code will give a downloadable .txt
file without redirecting to another page.上面的代码将提供一个可下载的
.txt
文件,而不会重定向到另一个页面。 The code will not give the result here as the file is created locally.由于文件是在本地创建的,因此代码不会在此处给出结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.