【问题标题】:How to force download of "index.html" file via an <a> tag in HTML如何通过 HTML 中的 <a> 标签强制下载“index.html”文件
【发布时间】:2020-02-27 16:02:47
【问题描述】:

我有一个在线配置编辑器here。配置编辑器制作为单页文件,即index.html 文件,通过链接托管。

我希望能够以一种在单击链接时触发下载index.html 文件的方式链接到此配置编辑器,而不是在浏览器中显示它。

我希望通过以下方式实现这一点 - 但它似乎不适用于 index.html 文件。有什么建议可以通过 HTML 或简单的 Javascript 代码解决这个问题吗?

<a href="https://[url]/index.html" download="editor">download here</a>

【问题讨论】:

  • 我认为你应该在你的后端实现一个文件下载器。如果你在 Express 中使用 NodeJS,你可以在这里查看stackoverflow.com/questions/7288814/…
  • 由于浏览器通常非常渴望呈现 html 页面,而不是下载它们,您可能必须通过在从后端传递文件时设置 Content-Disposition: attachment 标头来强制它。跨度>
  • 下载属性在html5中没有取值,见developer.mozilla.org/en-US/docs/Web/HTML/Element/a
  • 感谢您的意见。我什至会对一些简单的 vanilla javascript 解决方案感到满意——但对于下载 index.html 文件的这种边缘情况来说,即使这样似乎也很困难。任何香草 JS 建议表示赞赏!

标签: javascript html hyperlink download


【解决方案1】:

我最终得到了这个解决方案 - 欢迎任何改进它的意见。请注意,除非index.html 位于同一域中,否则此解决方案会导致 CORS 问题,但由于我恰好是这种情况,因此它可以根据需要工作。

HTML:

<a href="#" id="download-editor" class="btn-white">Offline editor</a>

Javascript:

<script>
  window.onload = function() {
    var a = document.getElementById("download-editor");
    a.onclick = function() {

    var url = 'https://canlogger.csselectronics.com/simple-editor/index.html'

    fetch(url).then(function(t) {
      return t.blob().then((b)=>{
        var a = document.createElement("a");
        a.href = URL.createObjectURL(b);
        a.setAttribute("download", 'config-editor.html');
        a.click();
      }
      );
    });
    }
  }
</script>

【讨论】:

    猜你喜欢
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    • 2014-03-03
    • 2022-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多