Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 262
JZ. Avatar asked Jul 05 '11 20:07

JZ.


1 Answers

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"
like image 155
Gal Avatar answered Sep 28 '22 06:09

Gal