How to download a CSV file in Ruby on Rails?

こ雲淡風輕ζ 提交于 2019-12-03 08:39:54

问题


In my InvoicesController I have this:

def index
  @invoices = current_user.invoices
  respond_to do |format|
    format.html
    format.xls
    format.csv # not working!
  end
end

In my index.html.erb view I have these two download links:

<%= link_to "Download as Excel", invoices_path(:format => "xsl") %>
<%= link_to "Download as CSV", invoices_path(:format => "csv") %>

The templates index.xsl.erb and index.csv.erb do exist as well.

The first link works, i.e. the Excel file gets downloaded to the user's computer. However, the CSV file is rendered in the browser and not downloaded.

What must I do to enable users to download CSV files as well?

Thanks for any help.


回答1:


Try specifying the appropriate content headers and explicitly rendering your index.csv.erb template in your format.csv handler block.

# app/controllers/invoices_controller.rb
format.csv do
    response.headers['Content-Type'] = 'text/csv'
    response.headers['Content-Disposition'] = 'attachment; filename=invoice.csv'    
    render :template => "path/to/index.csv.erb"
end



回答2:


Try this

format.csv do
  response.headers["Content-Type"] = "text/csv; charset=UTF-8; header=present"
  response.headers["Content-Disposition"] = "attachment; filename=invoices.csv"
end



回答3:


I recently discovered

render_csv

maybe check out this railscast (yay)



来源:https://stackoverflow.com/questions/17014912/how-to-download-a-csv-file-in-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!