代码之家  ›  专栏  ›  技术社区  ›  Ryan Florence

从控制器操作强制下载公共目录中的文件?

  •  1
  • Ryan Florence  · 技术社区  · 16 年前

    我做过这个:

    <% response.headers['Content-Disposition'] = "attachment; 
            filename=somefile.txt" -%>
    
    I am a text file!
    

    我想在不透露路径的情况下强制下载我的公用文件夹中的文件,所以我有一个控制器,它会检查一些参数来知道我的文件(在公用文件夹中)的位置,然后我想强制下载:

    <% response.headers['Content-Disposition'] = "attachment; 
            filename=#{@invoice.file_name}" %>
    
    How do I get the file content to be here rather than this text?
    

    2 回复  |  直到 16 年前
        1
  •  5
  •   Mike Buckbee    16 年前

    我认为 send_file 会做你想做的事。

    send_file '/path/to.file', :type => 'text/plain', :disposition => 'inline'
    
        2
  •  3
  •   Damien MATHIEU    16 年前

    定义标题不是视图的工作。在控制器中这样做会更干净。

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

    你保持你的东西干净(在你看来没有作业代码),并适当地强制下载你的文件。