开发者

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 < Appli开发者_运维技巧cationController
  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?


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'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜