代码之家  ›  专栏  ›  技术社区  ›  My Car

HTML或JavaScript:当点击HTML按钮时,如何触发.txt文件的下载?

  •  0
  • My Car  · 技术社区  · 2 年前

    我正在做的是当点击HTML按钮并且文件中的文本是在HTML文本字段中键入的字符串时,触发.txt文件的下载。但我不知道该使用HTML还是JavaScript代码,也不知道如何编写代码。

    我读了 the question 除了要下载的.txt文件的文本是在HTML文本字段中键入的字符串之外,它几乎是一样的。

    我的代码:

    HTML代码:

    <form action="/a" method="POST">
      <input
        type="text"
        value="String"
        name="string"
      />
    
      <input type="submit" value="Submit" />
    </form>
    

    当点击HTML按钮时,如何触发.txt文件的下载?我很感激你的帮助。提前谢谢你!

    1 回复  |  直到 2 年前
        1
  •  2
  •   Moudi    2 年前

    根据您的文件类型,修改类型以适应,以下是MIME类型列表 https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types

    要将文件下载为html,请将类型修改为text/html

    <form action="/a" method="POST">
    <input
        type="text"
        value="String"
        name="string"
        id="filename"
    
    />
    
    <input type="submit" value="Submit" />
    </form>
    <script>
    document.querySelector("form").addEventListener("submit", (e) => {
        e.preventDefault();
        const string = document.querySelector("#filename").value;
        const element = document.createElement("a");
        const file = new Blob([string], { type: "text/plain" });
        element.href = URL.createObjectURL(file);
        element.download = "test.txt";
        document.body.appendChild(element); // Required for this to work in FireFox
        element.click();
    });
    </script>