Text file download link (ruby on rails)
I want to add a download link to my html page. Download will be a .txt file. I have done this,
<a href="path_to_file/myfile.txt">click to download txt </a>
But the problem is, when a user clicks this link, instead of asking user to download the file, it simply shows the text in the browser.
How can I change this script to ask开发者_如何学编程 user to download the file (with the default download prompt dialog box)
UPDATE: Thanks all for the replies. I'm using ruby/rails on the server side.
Use rails send_file method
Didn't you forget set wright content-header at server side:
header("Content-Disposition: attachment; filename=\"myfile.txt\"");
- simple way - zip it.
- if is available php
header ( 'Content-Type: text/html'); header ( "Content-Disposition: 'attachment'; filename='text.txt'" ); include ('path_to_file/myfile.txt') exit;
You can do this in .htaccess
1. If you want only for this specific file:
<Directory path_to_file>
<Files myfile.txt>
<IfModule mod_headers.c>
ForceType application/octet-stream
Header set Content-Disposition attachment
</IfModule>
</Files>
</Directory>
2. If you want it to be for all the .txt
files under path_to_file
<Directory path_to_file>
<FilesMatch “.(?i:(txt))$”>
<IfModule mod_headers.c>
ForceType application/octet-stream
Header set Content-Disposition attachment
</IfModule>
</FilesMatch>
</Directory>
View : (Html file)
= link_to 'click to download txt', :controller => 'download', :action => 'test'
Download Controller :
def test file_path = 'path_to_file/myfile.txt' send_file file_path end
If your server supports php, you could use these lines:
header('Content-type: text/plain');
header('Content-disposition: attachment; filename="name.txt"');
readfile('name.txt');
Also see PHP: header Example #1
精彩评论