【问题标题】:Download a text file in HTML [duplicate]以 HTML 格式下载文本文件 [重复]
【发布时间】:2014-05-30 09:01:21
【问题描述】:

我想编写一个 html 代码来下载保存在文本文件中的用户输入的输入值。在下面的 html 中,当按下“保存”按钮时,输入值应在用户计算机中保存为 .text 文件。

<html>

<head>
    <script type="text/javascript">
        function write_below(form) {
            var input = document.forms.write.input_to_write.value;
            document.getElementById('write_here').innerHTML = "Your input was:" + input;
            return false;
        }
    </script>
</head>

<!--Insert more code here-->

<body>
    <form name='write' onsubmit='return write_below(this);'>
        <input type="text" name='input_to_write'>
        <input type="button" value="save" />
    </form>
    <div id='write_here'></div>
</body>

</html>

谁能帮我解决这个问题?

【问题讨论】:

  • 需要使用任何服务器端编码,例如 PHP 或 ASP.NET 来做同样的事情。
  • @MerlinRajaselvi 即使是服务器也无法将任意文件写入用户的计算机。
  • 但当然可以生成文件并触发下载提示,用户可以在其中决定是否保存文件以及保存文件的位置。参见例如stackoverflow.com/questions/2897619/…而如果你只是想在用户的电脑上存储信息,最好使用localstorage。
  • 您也可以use techniques like this。这里有一些可能的误解和普遍的 FUD 传播。
  • @user3127499, that's not how it works

标签: javascript html


【解决方案1】:

数据 URI 方案是一种 URI 方案(统一资源标识符方案),它提供了一种在网页中包含内嵌数据的方法,就好像它们是外部资源一样。

您可以使用以下 uri 来模拟外部文本文件。只需将代码复制到您的地址栏,看看会发生什么。

data:application/txt,Hello World!

完整代码或查看fiddle

<html>

<head>
    <title>Fake download via datauri</title>
</head>

<body>

    <textarea cols="50" rows="10" id="source">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</textarea>
    <br>
    <button type="button" id="save" title="Save as text file">Save</button>

    <script type="text/javascript">
        // when document is ready
        document.getElementById("save").onclick = function() {
            // when clicked the button
            var content = document.getElementById('source').value;
            // a [save as] dialog will be shown
            window.open("data:application/txt," + encodeURIComponent(content), "_self");
        }
    </script>
</body>

</html>

一些老式浏览器不支持此功能。 Full list

此外,请确保内容不要太长,以防浏览器拒绝请求。

【讨论】:

  • 感谢您的帮助。这就是我正在寻找的解决方案。
【解决方案2】:

您可以通过创建一个 blob-url 和指向它的链接来做到这一点。链接(而不是按钮!)必须具有 download 属性,该属性指定文件的默认名称。

但是,因为我不确定这个属性的兼容性,所以我设置了二进制 mime 类型,因为 text/plain 被浏览器识别并且只是打开而不是显示下载窗口。

var text = "foo\nbar\nbaz";

var fileBlob = new Blob([text], {type: "application/octet-binary"});

var link = document.createElement("a");
link.setAttribute("href", URL.createObjectURL(fileBlob));
link.setAttribute("download", "HelloWorld.txt");
link.appendChild(document.createTextNode("Save file"));
document.body.appendChild(link);

【讨论】:

    【解决方案3】:

    通过使用以下 PHP 函数,您可以下载文件:

    function dowld($path)
    {
        // get the file mime type using the file extension
        $mime = get_mime_by_extension($path); // Build the headers to push out the file properly.
        header('Content-Description: File Download');
        header('Pragma: public');
        header('Expires: 0');
        header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
        header('Cache-Control: private',false);
        header('Content-Type: '.$mime);
        header('Content-Disposition: attachment; filename="'.basename($path).'"');
        header('Content-Transfer-Encoding: binary');
        header('Connection: close');
        ob_clean();
        flush();
        readfile($path);
    }
    

    $path 是指要下载的文件的路径。

    例如:

    dowld('./files/myfile.txt');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-24
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 2015-12-04
      • 2012-03-20
      • 2019-01-08
      相关资源
      最近更新 更多