Html 如何创建可下载的文本文件链接?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9208657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 22:24:06  来源:igfitidea点击:

How to create downloadable link to text file?

htmlhyperlinkdownload

提问by u775856

The purpose is to download the dumped backup.sqlfile after running the sql dumping script (from PHP). Normally, the dumped .sqlfile is outputted (written) on the server. Then when i make a href link to that file like <a href="backup.sql">Download File</a>, the file is opening inside the browser on clicking, instead of being downloading.

目的是backup.sql在运行sql转储脚本(来自PHP)后下载转储文件。通常,转储的.sql文件在服务器上输出(写入)。然后,当我创建指向该文件的 href 链接时<a href="backup.sql">Download File</a>,该文件将在单击时在浏览器中打开,而不是正在下载。

  • i just want to make a simple HREF LINK(to such a text file) which show up with "Save as.." dialog on simple Left Click.
  • 我只想制作一个简单的HREF 链接(到这样的文本文件),在简单的左键单击上显示“另存为..”对话框。

How it could be done?

怎么做?

采纳答案by Rob W

Add the following lines to your .htaccessfile.

将以下行添加到您的.htaccess文件中。

<Files "backup.sql">
ForceType applicaton/octet-stream
Header set Content-Disposition attachment
</Files>

回答by Gokul N K

Or you could just use the new HTML5 property downloadin the anchor tag of your html.

或者您可以download在 html 的锚标记中使用新的 HTML5 属性。

The code will look something like

代码看起来像

<a download href="path/to/the/download/file"> Clicking on this link will force download the file</a>

It works on firefox and chrome latest version. Should I mention that I didn't check it in IE? :P

它适用于 Firefox 和 chrome 最新版本。我应该提到我没有在 IE 中检查它吗?:P

回答by vikki

Another option is serving it with in a .php file eg download.php

另一种选择是在 .php 文件中提供它,例如 download.php

have this in download.php

在download.php中有这个

    $path = "backup.sql"
    header("Content-Type: application/octet-stream");    //

    header("Content-Length: " . filesize($path));    

    header('Content-Disposition: attachment; filename='.$path);

    readfile($path); 

then

然后

<a href="download.php">Download File</a>

回答by Vaulter

Just for referencing in this thread https://stackoverflow.com/a/56664507/766644

仅供参考此线程 https://stackoverflow.com/a/56664507/766644

If you have all export data (your .sql text e.g.) available on client, you could just

如果您有客户端上可用的所有导出数据(例如您的 .sql 文本),您可以

const blob = new Blob([fileContent], { type: 'text/plain' });
const a = document.createElement('a');
a.setAttribute('download', fileName);
a.setAttribute('href', window.URL.createObjectURL(blob));
a.click();