views:

71

answers:

2

I've done this:

<% response.headers['Content-Disposition'] = "attachment; 
        filename=somefile.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?

+1  A: 

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.

Damien MATHIEU
Oh and I almost forgot that if your file is too big, you can stream it with send_file.http://api.rubyonrails.org/classes/ActionController/Streaming.html
Damien MATHIEU
It's a pdf, I get an error saying that no such file exists. If I copy that path and paste it into my browser the file does exist. I really hope I can get this work, otherwise I have to refactor a bunch of stuff :(
rpflo
You should put the system path. Not the http server one.
Damien MATHIEU
I see, thank you. After I asked the question I realized I was asking for a bandaid anyway, so I've done some reworking.
rpflo
+1  A: 

I think that send_file would do what you want.

send_file '/path/to.file', :type => 'text/plain', :disposition => 'inline'
Mike Buckbee
Getting a "Cannot read file /path/to/file.pdf", but it is there.
rpflo
Can the user (under which you web server runs) access all directories up to the file?
Aaron Digulla
I refactored everything with the help of this post: http://harrylove.org/2008/12/22/protected-file-downloads-with-ruby-on-rails-and-paperclip, which in the end uses send_file.
rpflo