Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create downloadable file in ruby on rails

Visiting the page

localhost:3000/download_me

calls the controller action download_me in controller foo.

class foo < ApplicationController
  def download_me
    # a file is created here i.e. temp.csv in directory C:\
  end
end

The controller shall create a temporary csv file and after that trigger a download in the browser that is visiting the page.

How can I do that?

like image 714
Sebastian Müller Avatar asked May 23 '11 13:05

Sebastian Müller


People also ask

How to download file in Ruby?

Plain old Ruby The most popular way to download a file without any dependencies is to use the standard library open-uri . open-uri extends Kernel#open so that it can open URIs as if they were files. We can use this to download an image and then save it as a file.


1 Answers

Is there any reason you want to store the temp file on your server? If so something like this should suffice (using fastercsv, which you'll need to install):

require 'fastercsv'
FILE_PATH= "root/to/tmpfile.csv"

FasterCSV.open(FILE_PATH, "w") do |csv|
    csv << 'add some data'
end

send_file file_path, :type=>'text/csv'

I suggest you probably don't need to store the file though so just replace the FasterCSV.open line with:

csv = FasterCSV.generate do |csv|

Then spit out the csv as the response:

send_data csv, :type=> 'text/csv'
like image 183
Yule Avatar answered Oct 04 '22 15:10

Yule