简体   繁体   English

单击按钮而不是打开新选项卡(HTML 或 JavaScript)时如何触发文件下载

[英]How to trigger a file download when clicking an button instead opening a new tab (HTML or JavaScript)

I have tried following details:我尝试了以下细节:

  1.  <form method="get" action="file.doc"> <button type="submit">Download!</button> </form>
  2.  <a href="path_to_file" download="proposed_file_name">Download</a>
  3.  <a class="btn btn-success" href="https://www.google.com" target="_blank">Google</a>
  4.  <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.

相关问题 单击 HTML 按钮或 JavaScript 时如何触发文件下载 - How to trigger a file download when clicking an HTML button or JavaScript 单击 HTML 按钮时如何触发带有文本区域内容的文件下载 - How to trigger a file download with text area content when clicking an HTML button <a>在现代浏览器中</a>单击html <a>标记或javascript</a>时如何触发文件下载 - How to trigger a file download when clicking an html <a> tag or javascript in a modern browser 单击 HTML 链接<a>到其他网站</a>时如何触发文件下载 - How to trigger a file download when clicking an HTML Link <a> to other website 文件(pdf、jpg、png)下载而不是在新标签中打开 - File (pdf, jpg, png) download instead of opening in new tab 使用 ng-click 指令单击按钮时,如何防止在使用 puppeteer 抓取期间打开新标签页? - How to prevent opening a new tab during scraping with puppeteer, when clicking a button with ng-click directive? 单击功能区按钮时如何在新选项卡而不是新窗口中打开Web资源 - How to open a web resource in a new tab instead of a new window when clicking a ribbon button 单击链接而不下载时如何在新选项卡中显示pdf? - how to display pdf in new tab when clicking on link without download? 如何在不打开新标签的情况下在Google Chrome扩展程序中下载文件 - How to download file in google chrome extension without opening a new tab (HTML) 下载 PDF 文件,而不是单击时在浏览器中打开它们 - (HTML) Download a PDF file instead of opening them in browser when clicked
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM