Ruby on rails, forcing the user to download the tmp file

I created a file in the tmp directory with the following controller code:

  def download
    file_path = "#{RAILS_ROOT}/tmp/downloads/xxx.html"
    data = render_to_string( :action => :show, :layout => nil )
    File.open(file_path, "w"){|f| f << data }
    flash[:notice] = "saved to #{file_path}"
  end

This creates the file that I need in the tmp directory, and I want the user to download this file.

On my local machine, the file is saved to a path, for example:

/Users/xxxx/Documents/Sites/xxxx/Website/htdocs/tmp/downloads/xxxx.html

And on a live server, this URL will be completely different.

I was wondering how to get the user to download this xxxx.html?

PS If I put ...

redirect_to file_path

... on the controller, he just gives me a route that was not found.

Greetings.

+3
source share
2 answers

Take a look at the send_file method . It looks something like this:

send_file Rails.root.join('tmp', 'downloads', 'xxxxx.html'), :type => 'text/html', :disposition => 'attachment'

: disposition = > 'attachment' . "inline", , . nginx Rails-, (, environment/production.rb):

# For nginx:
config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'
+4

URL-, . , URL- /a/b.txt, #{Rails.root}/public/a/b.txt, , .

:

def download
  base_path = "downloads/xxx.html"

  system_path = File.expand_path("public/#{base_path}", Rails.root)
  url_path = "/#{base_path}"

  File.open(file_path, "w") do |f|
    f.puts render_to_string(:action => :show, :layout => nil)
  end

  flash[:notice] = "saved to #{base_path}"

  redirect_to(url_path)
end

, -, public/. , .

, , :

render(:action => :show, :layout => nil, :content_type=> 'application/octet-stream')
+3

All Articles