2011-07-05 2 views
5

파일을 다운로드하려면 : 파이어 폭스와 크롬을 사용CSV 사파리보기에 렌더링하지만 나는 내가 정의 MIME 타입 설정 한

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

: 내 컨트롤러에서

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 블록을 , .csv는 다운로드 된 파일로 렌더링됩니다. Safari를 사용하면 .csv가 뷰로 렌더링됩니다.이 파일을 어떻게 변경하고 강제로 파일로 다운로드 할 수 있습니까?

enter image description here

답변

9

이 작동하지 않는 경우,

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

감사합니다. response.headers 메소드는 훌륭하게 작동합니다. –

0

나는이이 방법을 사용해보십시오

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 

을 시도해보십시오

문제의 스크린 샷을 참조하십시오 오래 된 Rails 2 앱에서 작업하는 경우대신 send_data을 사용합니다. 제어기의. 예 :

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