Force download of file in the public directory from a controller action?
I've done this:
<% response.headers['Content-Disposition'] = "attachment;
filename=so开发者_如何学Pythonmefile.txt" -%>
I am a text file!
I'd like to force the download of a file in my public folder without revealing the path, so I've got a controller than checks some params to know the location of my file (in my public folder) and then I'd like to force the download:
<% response.headers['Content-Disposition'] = "attachment;
filename=#{@invoice.file_name}" %>
How do I get the file content to be here rather than this text?
Is there a way to do that?
I think that send_file would do what you want.
send_file '/path/to.file', :type => 'text/plain', :disposition => 'inline'
Defining the headers isn't the view's job. Doing it in the controller would be much cleaner. In fact you don't need any html view to render that kind of files.
Doing something like this would be more appropriate :
def action
response.headers['Content-Disposition'] = 'attachment; filename=somefile.txt'
return render(:text => File.read('/path/to/your/file.txt')
end
You keep your thing clean (not having job code in your view) and appropriately force the download on your file.
精彩评论