2011-07-05 30 views
5

我已經配置了一個自定義MIME類型的文件:CSV呈現在Safari的看法,但我想它下載

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 

和respond_to代碼塊在我的控制器:

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

使用Firefox和Chrome .csv呈現給下載的文件。使用Safari將.csv渲染爲視圖:我如何更改並強制它以文件形式下載?

看到問題的屏幕截圖:

enter image description here

回答

9

嘗試

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 

如果這不起作用,請嘗試使用

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

謝謝。 response.headers方法效果很好。 –

0

我有這個問題的方法在舊的Rails 2應用程序中使用send_data而不是render在控制器中。例如:

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