Rails CSV attachment opens in browser instead of d

2019-08-03 09:24发布

In my rails 3 application I provide a CSV template for users to download. Instead of downloading it simply opens the text in a new tab. Here is the code:

<a href="/templates/myFile.csv" target="_blank">click here</a>

This was working for me previously and I'm not sure what could have changed to break it. Other questions similar to this suggest adding target='_blank' or changing the headers but I haven't had much luck doing so.

I don't think it should make a difference, but this link is inside of a modal who's body comes from here:

<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>

2条回答
【Aperson】
2楼-- · 2019-08-03 09:49

You can use send_file method:

def download_file(file_path)
   send_file(file_path, :type => 'text/csv', :disposition => "attachment")
end

You can add this method to a controller and routes, then use it in your views:

link_to "Download", download_file_path('some_file.csv')
查看更多
一纸荒年 Trace。
3楼-- · 2019-08-03 09:51

target="_blank" will open the file in a new tab. But it depends upon browser setting whether to open to the file in tab or to ask if the file is to be downloaded or not.

查看更多
登录 后发表回答