Ruby on Rails Send_File Doesn't Work Until I Refresh the Page

send_file in rails does not download to browser - instead loads in browser window directly

You need to add disposition: 'attachment' to your send_file option hash (or at least ensure that you do not have disposition: 'inline' set, since 'attachment' should be the default).

If this is not the issue, if you are using Turbolinks, as mentioned in other answers you need to disable Turbolinks on the link by setting data-turbolinks="false" in your link element (e.g.: data: {turbolinks: false} in your link_to tag helper).

Finally, here are some other things to try if this doesn't work:

  • Set type to 'application/vnd.ms-excel', the valid MIME type for XLS files.
  • Set the download="mything.xls" html5 attribute on the link tag directly (e.g.: download: 'mything.xls' in your link_to tag helper.

Ruby on Rails send_file, code in controller action running twice

The issue ended up being caused by a turbolinks gotcha.

Resolved with:

<%= link_to document.file.file.filename, document_path(document), 'data-no-turbolink' => true %>

send_file return value

No, there is no way to confirm download completion or success with send_file. From this question: Can we find out when a Paperclip download is complete? :

send_file creates the file and then passes a special header to tell
the webserver telling it what to send. Rails doesn't actually send the
file at all, it sets this header which tells the webserver to send the
file but then returns immediately, and moves on to serve another
request. To be able to track if the download completes you'd have to
occupy your Rails application process sending the file and block until
the user downloads it, instead of leaving that to the webserver (which
is what its designed to do). This is super inefficient.

You may be able to do something using cookies and JavaScript on the client.
See this question: Rails File Download And View Update - Howto?

In rails can't we use send_file and redirect_to together? Gives Render and/or redirect were called multiple times error

You are trying to send two responses. One being file data and one being a redirect. Rails doesn't allow you to do this in a controller. It can be achieved with javascript but it's a little hacky. See this: Rails how do I - export data with send_data then redirect_to a new page?



Related Topics



Leave a reply



Submit