JZ.
JZ.

Reputation: 21877

CSV renders in Safari view but I want it to download a file

I have configured a custom mime type:

ActionController::Renderers.add :csv do |csv, options|
  self.content_type ||= Mime::CSV
  self.response_body  = csv.respond_to?(:to_csv) ? csv.to_csv : csv
end

and a respond_to block in my controller:

respond_to do |format|
    format.html
    format.csv { render :csv => csv_code}
  end   

Using Firefox and Chrome, the .csv renders to a file which is downloaded. Using Safari the .csv is rendered as a view: How can I change this and force it to download as a file?

See a screen shot of the problem:

enter image description here

Upvotes: 5

Views: 4049

Answers (2)

Jeremy Weathers
Jeremy Weathers

Reputation: 2554

The way I have this working in an old Rails 2 app is using send_data instead of render in the controller. E.g.:

def csv
  ... # build data
  send_data csv_data_as_string, :filename => "#{filename}.csv", :type => 'text/csv'
end

Upvotes: 0

Gal
Gal

Reputation: 23662

Try

respond_to do |format|
    format.html
    format.csv do
        response.headers['Content-Type'] = 'text/csv'
        response.headers['Content-Disposition'] = 'attachment; filename=thefile.csv'    
        render :csv => csv_code
    end
end 

if this doesn't work, try using

send_file "path/to/file.csv", :disposition => "attachment"

Upvotes: 10

Related Questions