I am new to Ruby on Rails. I am using Ruby 2 and Rails 4. I want to download a file using rails. But when I enter the path it does not show the html page, but it opens a download box and click on ok it downloads. My codes are below. Please help me if any body can. Thank you.

In controller:

def download
  send_file(
    "#{Rails.root}/public/robots.txt",
    filename: "robots.txt",
    type: "application/txt"
  )
end

In download.html.erb:

<%= link_to 'Download', academics_download_path(:format => "txt")  %>
有帮助吗?

解决方案

For each request you can only make one response. Sending a file is a response, so you can't do anything else - the view is not even being rendered.

If you want to display a page first, you need to create a new action to display html page and then another to send the file.

# controller

def download_file
  send_file(
    "#{Rails.root}/public/robots.txt",
    filename: "robots.txt",
    type: "application/txt"
  )
end

def download
end

# view
<%= link_to 'Download', academics_download_file_path(:format => "txt")  %>

Remember to update your routes as well (requires server restart)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top