How can I send binary data from Sinatra?

橙三吉。 提交于 2019-12-04 16:23:51

问题


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.


回答1:


you can just return binary data:

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



回答2:


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



回答3:


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




回答4:


I used something like this:

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


来源:https://stackoverflow.com/questions/6083974/how-can-i-send-binary-data-from-sinatra

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!