10

Good day! I want to download autogenerated file qwerty.csv, but it returns only text "12345" (without file). Can you help me?

UI

<script type="text/javascript">
function getCsv() {
    var ids = getSelectedRecordIds();
    $.post('/payments/form_csv.csv', { ids: ids }, function(data) {});
}
</script>

Controller

def form_csv
    csv_string = CSV.generate do |csv|
        csv << ["12345"]
    end

    respond_to do |format|
        format.csv {
            send_data csv_string, :type => 'text/csv; charset=utf-8; header=present', :disposition => "attachment; filename=qwerty.csv", :filename => "qwerty.csv"
        }
    end
end

In console

Started POST "/payments/form_csv.csv" for 127.0.0.1 at 2012-06-18 18:18:11 +0400 
Processing by PaymentsController#form_csv as CSV
  Parameters: {"ids"=>["18\n\t  "]}
  Rendered text template (0.0ms)
Sent data qwerty.csv (0.4ms)
Completed 200 OK in 2ms (Views: 0.4ms | ActiveRecord: 0.0ms)

But there are no file prompt...

AnDragFag
  • 181
  • 1
  • 1
  • 5
  • Maybe it's just an issue how you registered your applications/MIME-types. What happens when you click on a *.csv file in your file browser? Does LibreOffice (or Excel) open automatically? Unknown/unregistered txt MIME-types might always be shown in your browser. – Christoph Petschnig Jun 18 '12 at 15:08
  • >> What happens when you click on a *.csv file in your file browser? Does LibreOffice (or Excel) open automatically? Unfortunately, yes, Excel open it automatically =( Very similar topic (without decision) - http://stackoverflow.com/questions/7597414/how-to-handle-csv-download-prompt-through-a-post-request-in-rails – AnDragFag Jun 18 '12 at 15:45
  • @AnDragFag I guess it case of over smart browser where which display CSV data on browser . set this and hope this help `config.action_dispatch.x_sendfile_header="X-Sendfile"` – Viren Jun 18 '12 at 17:19

1 Answers1

8

Ow, it works without ajax, as a form submit!

There is same problem in this topic: http://www.ruby-forum.com/topic/111107

Make the form a non-AJAX form I try it… And it works!

Controller

def form_csv
    csv = get_csv
    send_csv(csv)
end

def get_csv
    result = CSV.generate do |csv|
        csv << ["12345"]
    end
    return result
end

def send_csv(csv)
    send_data csv, :type => 'text/csv; charset=utf-8; header=present', :disposition => 'attachment; filename=payments.csv'
end

UI

function getCsv() {
    var ids = getSelectedRecordIds();
    params = {ids: ids}
    post_to_url("/payments/form_csv", params);
}

where post_to_url - is method from JavaScript post request like a form submit topic.

And after all

protect_from_forgery :except => :form_csv

in controller to disable authentication token for pay_csv request.

Ugly decision, but it helps me… May be is there more right way?

Viren, I'll try it, thanks!

ka8725
  • 2,490
  • 1
  • 22
  • 35
AnDragFag
  • 181
  • 1
  • 1
  • 5