[英]How to download a text file onclick using javascript or HTML
I just want to download a .txt on click it. 我只想单击下载一个.txt。 i am using the below html code:
我正在使用以下html代码:
<a href="d:/file.txt">Download</a>
this code is working for .docx files not for .txt file. 此代码适用于.docx文件,不适用于.txt文件。
Text files are displayed in the browser when the content-type is sent as text. 当内容类型作为文本发送时,文本文件显示在浏览器中。 You should Try to send it with a different content-type or use a language such as PHP to send it as a download.
您应该尝试使用其他内容类型发送它,或使用PHP之类的语言将其作为下载发送。
please try 请试试
<a href="d:/file.txt" download="my_text_file">Download</a>
The download="my_text_file"
attribute indicates that the target will be downloaded when clicked on the link.. and my_text_file will be new name for that file... download="my_text_file"
属性指示单击链接时将下载目标。.并且my_text_file将是该文件的新名称...
You need to specify the file:
protocol. 您需要指定
file:
协议。 Otherwise, the browser thinks that d:
is a protocol name. 否则,浏览器认为
d:
是协议名称。 You also need the download
attribute to make it download the file instead of displaying it in the browser. 您还需要
download
属性来使其下载文件,而不是在浏览器中显示它。
So it should be: 因此应该是:
<a href="file:///d:/file.txt" download>Download</a>
But this seems pointless. 但这似乎毫无意义。 The file
d:/file.txt
is already on your computer, why do you need to download it? 文件
d:/file.txt
已在您的计算机上,为什么需要下载它? Normally you download a file from the server to the client. 通常,您将文件从服务器下载到客户端。
To expand on the answer from @barmar: 要扩展@barmar的答案:
Taking the jquery question tag into consideration, check out Download File Using jQuery . 考虑到jquery的问号,签出使用jQuery下载文件 。 Here's the code example from that post:
这是该帖子中的代码示例:
$('a').click(function(e) {
e.preventDefault(); //stop the browser from following
window.location.href = 'uploads/file.doc';
});
<a href="no-script.html">Download now!</a>
You can change the value assigned to window.location.href to the file you would like to download. 您可以将分配给window.location.href的值更改为要下载的文件。
Try this: 尝试这个:
<a href="d:/file.txt" download>Download</a>
It is working for me. 它为我工作。
Cheers 干杯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.