rails won't send_data as file

2019-01-15 13:56发布

问题:

I'm having problems with Rails method: send_data

Here's my action:

def export
  send_data(current_user.contacts.to_csv,
    type: 'text/csv; charset=utf-8; header=present',
    disposition: 'attachment; filename=contacts.csv'
  )
end

This will not promt for a download, it just render the result on the screen. I've tried both pow and thin servers.

I can't figure out what I'm doing wrong?

I'm using rails 4.0.0.beta

EDIT:

CURL headers:

< HTTP/1.1 200 OK
< X-Frame-Options: SAMEORIGIN
< X-XSS-Protection: 1; mode=block
< X-Content-Type-Options: nosniff
< X-UA-Compatible: chrome=1
< X-XHR-Current-Location: /contacts/export
< Content-Disposition: attachment; filename=contacts.csv
< Content-Transfer-Encoding: binary
< Content-Type: text/csv; charset=utf-8; header=present
< Cache-Control: private
< ETag: "48d3d8bd1c8d25cafb82ab705e4875ab"
< Set-Cookie: request_method=GET; path=/
< X-Request-Id: c2588883-f3f9-4f68-8a8c-0de758c47288
< X-Runtime: 0.185206
< Connection: close
< Server: thin 1.5.0 codename Knife

回答1:

The answers here, are for turbolinks classic. There is a newer notation on newer versions of turbolinks:

<a href="/" data-turbolinks="false">Disabled</a>

https://github.com/turbolinks/turbolinks#disabling-turbolinks-on-specific-links



回答2:

I figured it out.

It was turbolinks that was messing it all up. I added data-no-turbolink to the export link and now it works as expected.



回答3:

send_data has an option hash, so type, disposition and filename need to be set in a hash:

def export
  send_data(current_user.contacts.to_csv,
  type: 'text/csv', disposition: 'attachment', filename: 'contacts.csv')
end