2009-10-09 50 views
1

我已经做到了这一点:强制从控制器操作下载公共目录中的文件?

<% response.headers['Content-Disposition'] = "attachment; 
     filename=somefile.txt" -%> 

I am a text file! 

我想迫使我的公用文件夹文件的下载没有透露的路径,所以我有一个控制器比检查一些PARAMS知道位置(我的公共文件夹),然后我想强制下载:

<% response.headers['Content-Disposition'] = "attachment; 
     filename=#{@invoice.file_name}" %> 

How do I get the file content to be here rather than this text? 

有没有办法做到这一点?

回答

5

我认为send_file会做你想做的。

send_file '/path/to.file', :type => 'text/plain', :disposition => 'inline' 
+1

获取“无法读取文件/path/to/file.pdf”,但它在那里 – 2009-10-09 15:47:29

+0

用户(您的Web服务器运行时)是否可以访问所有文件目录到文件? – 2009-10-09 16:03:35

+0

我在这篇文章的帮助下重构了所有内容:http://harrylove.org/2008/12/22/protected-file-downloads-with-ruby-on-rails-and-paperclip,它最后使用send_file。 – 2009-10-09 17:12:01

3

定义标题不是视图的工作。在控制器中做它会更干净。 实际上你不需要任何html视图来渲染那种文件。

做这样的事情会更合适:

def action 
    response.headers['Content-Disposition'] = 'attachment; filename=somefile.txt' 
    return render(:text => File.read('/path/to/your/file.txt') 
end 

你保持你的东西干净(没有在你看来职位代码),并适当地迫使文件的下载。

+1

哦,我差点忘了,如果你的文件太大,你可以使用send_file进行流式处理。 http://api.rubyonrails.org/classes/ActionController/Streaming.html – 2009-10-09 15:37:52

+0

这是一个pdf,我得到一个错误,说没有这样的文件存在。如果我复制该路径并将其粘贴到我的浏览器中,则文件确实存在。我真的希望我能得到这个工作,否则我不得不重构一堆东西:( – 2009-10-09 15:39:47

+0

你应该把系统路径。不是http服务器之一。 – 2009-10-09 20:29:32