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

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

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

    我已经做到了:

    <% 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 回复  |  直到 15 年前
        1
  •  5
  •   Mike Buckbee    15 年前

    send_file 我会做你想做的。

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

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

    这样做更合适:

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

    你保持你的东西干净(你的视图中没有工作代码),并适当地强制下载你的文件。