Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I send binary data from Sinatra?

Tags:

sinatra

I want to send binary data from a Sinatra application so that the user can download it as a file.

I tried using send_databut it gives me an undefined method 'send_data'

How could I achieve this?

I could write the data to a file and then use send_filebut I would rather avoid doing this.

like image 407
Nerian Avatar asked May 21 '11 19:05

Nerian


3 Answers

you can just return binary data:

get '/binary' do
  content_type 'application/octet-stream'
  "\x01\x02\x03"
end
like image 196
Konstantin Haase Avatar answered Nov 06 '22 22:11

Konstantin Haase


I did it like this:

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
like image 24
Nerian Avatar answered Nov 07 '22 00:11

Nerian


The current version of Sinatra has a way to stream data:

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

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

like image 7
Jeremy Stephens Avatar answered Nov 07 '22 00:11

Jeremy Stephens