3

我有一个 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 方法。如果流媒体在这段时间内阻塞了我的服务器,那么我愿意接受替代方案。

4

1 回答 1

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 文件中。但这有效。

于 2012-11-12T05:01:16.720 回答