用于下载文件的Ruby Sinatra应用程序(作为流式传输)

时间:2012-11-12 04:21:50

标签: ruby sinatra

我有一个sinatra应用程序,我想在其中进行下载功能。此下载从表中获取数据,并为用户提供excel下载。

require 'csv'
get '/download' do 
     data = [{:name => "john", :age => 12, :state => 'ca'}, {:name => "tony", :age => 22, :state => 'va'}]

     # I want to download this data as excel file and the content of file should be as follows:
     # name,age,state
     # john,12,ca
     # tony,22,va
     # I don't want to save data as a temp file on the server and then throw to user for download 
     # rather I want to stream data for download on the browser. So I used this, 
     # but it is not working

     send_data (data, :type => 'application/csv', :disposition => 'attachment')
end

我做错了什么?或者如何实现,我想做什么?我试图关注http://sinatra.rubyforge.org/api/classes/Sinatra/Streaming.html

更新: 我没有和sinatra的send_data方法结婚。如果流媒体阻止我的服务器持续一段时间,那么我愿意接受替代方案。

1 个答案:

答案 0 :(得分:5)

get '/download' do 
    data = [{:name => "john", :age => 12, :state => 'ca'}, {:name => "tony", :age => 22, :state => 'va'}]

    content_type 'application/csv'
    attachment "myfilename.csv"
    data.each{|k, v|
       p v
    }
end

这对我有用。我知道它不完整,因为我必须在带有换行符的excel文件中添加标题和逗号。但这很有效。