How to force fully download txt file on link?

拈花ヽ惹草 提交于 2019-12-17 10:59:17

问题


I have one simple text file and I want to download that file on any anchor tag link.

But when I click on that link txt file shown me but not downloaded.

I have try this code

<html>
    <head>
        <title>File</title>
    </head>
    <body>
        <a href="test.txt">Click here</a>
    </body>
</html>

回答1:


Download file when clicking on the link (instead of navigating to the file):

<a href="test.txt" download>Click here</a>

Download file and rename it to mytextdocument.txt:

<a href="test.txt" download="mytextdocument">Click here</a>

The download attribute specifies that the target will be downloaded when a user clicks on the hyperlink.

This attribute is only used if the href attribute is set.

The value of the attribute will be the name of the downloaded file. There are no restrictions on allowed values, and the browser will automatically detect the correct file extension and add it to the file (.img, .pdf, .txt, .html, etc.).

If the value is omitted, the original filename is used.




回答2:


You can use the Content-Disposition header.

You can do it with PHP or with .htaccess.

PHP:

<?php
header("Content-Disposition: attachment");
header("Content-Type: text/plain"); // optional
readfile("yourfile.txt");
?>

And then you can either use the PHP's URL or redirect the TXT's one to it. If you want to use the PHP's URL but want to save the file with the original name you can swap this line in there:

header("Content-Disposition: attachment; filename=yourfile.txt");

.htaccess:

<Files yourfile.txt>
    Header set Content-Disposition attachment
</Files>



回答3:


You can do this

<a href="data:text/plain;charset=UTF-8,test.txt" download>Click here</a>

Or in my case I needed something more dynamic

var downloadFile = function(url){
  let a = document.createElement('a');
  a.href = 'data:text/plain;charset=UTF-8,' + '' + url;
  a.download = url.substr(url.lastIndexOf('/') + 1);
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

The main difference was appending

data:text/plain;charset=UTF-8,

to my text file url

downloadFile('http://my.txt');




回答4:


Text files are displayed in the browser when the content-type is sent as text. You'd have to change the server to send it with a different content-type or use a language such as PHP to send it as a download.




回答5:


This will download your text file, and rename it :

 <a href="http://www.example.com/myfile.txt" download="My Text File">click here</a>  


来源:https://stackoverflow.com/questions/21088376/how-to-force-fully-download-txt-file-on-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!