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?
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.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With