2011-05-21 60 views
16

我想從Sinatra應用程序發送二進制數據,以便用戶可以將它作爲文件下載。如何從Sinatra發送二進制數據?

我嘗試使用send_data,但它給了我一個undefined method 'send_data'

我怎麼能做到這一點?

我可以將數據寫入文件,然後使用send_file但我寧願避免這樣做。

回答

27

你可以只返回二進制數據:

get '/binary' do 
    content_type 'application/octet-stream' 
    "\x01\x02\x03" 
end 
7

我做了這樣的:

get '/download/:id' do 
    project = JSON.parse(Redis.new.hget('active_projects', params[:id])) 
    response.headers['content_type'] = "application/octet-stream" 
    attachment(project.name+'.tga') 
    response.write(project.image) 
end 
7

西納特拉的當前版本有辦法流數據:

get '/' do 
    stream do |out| 
    out << "It's gonna be legen -\n" 
    sleep 0.5 
    out << " (wait for it) \n" 
    sleep 1 
    out << "- dary!\n" 
    end 
end 

來源:http://www.sinatrarb.com/intro#Streaming%20Responses

+0

更多流善良:http://www.sinatrarb.com/contrib/streaming.html – 2013-02-08 18:07:14

+1

+1 HIMYM裁判 – nurettin 2013-06-03 07:52:16

0

我以前是這樣的:

require 'sinatra' 

set :port, 8888 
set :bind, '0.0.0.0' 
filename = 'my_firmware_update.bin' 

get '/' do 
    content_type 'application/octet-stream' 
    File.read(filename) 
end 
相關問題