Rails CSV附件在浏览器中打开而不是下载

Jos*_*osh 1 csv ruby-on-rails file attachment

在我的rails 3应用程序中,我提供了一个CSV模板供用户下载.而不是下载它只是在新选项卡中打开文本.这是代码:

<a href="/templates/myFile.csv" target="_blank">click here</a>
Run Code Online (Sandbox Code Playgroud)

这对我以前很有用,我不知道有什么可以改变来打破它.与此类似的其他问题建议添加target='_blank'或更改标题,但我没有太多运气这样做.

我不认为它应该有所作为,但这个链接是在一个模态中,谁的身体来自这里:

<div class="modal hide" id="helpModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <%= modal_header "Help" %>
   <div class="modal-body">
    <%= render 'help' %>
  </div>
  <div class="modal-footer">
    <button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

小智 5

您可以使用send_file方法:

def download_file(file_path)
   send_file(file_path, :type => 'text/csv', :disposition => "attachment")
end
Run Code Online (Sandbox Code Playgroud)

您可以将此方法添加到控制器和路由,然后在视图中使用它:

link_to "Download", download_file_path('some_file.csv')
Run Code Online (Sandbox Code Playgroud)