如何从Sinatra发送二进制数据?

如何从Sinatra发送二进制数据?,sinatra,Sinatra,我想从Sinatra应用程序发送二进制数据,以便用户可以将其作为文件下载 我尝试使用send\u data,但它给了我一个未定义的方法“send\u data” 我怎样才能做到这一点 我可以将数据写入文件,然后使用send\u file,但我宁愿避免这样做。我这样做: get '/download/:id' do project = JSON.parse(Redis.new.hget('active_projects', params[:id])) response.headers['c

我想从Sinatra应用程序发送二进制数据,以便用户可以将其作为文件下载

我尝试使用
send\u data
,但它给了我一个
未定义的方法“send\u data”

我怎样才能做到这一点

我可以将数据写入文件,然后使用
send\u file
,但我宁愿避免这样做。

我这样做:

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
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

您可以只返回二进制数据:

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

Sinatra的当前版本提供了一种数据流的方式:

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
get'/'do
流出|

out我用了这样的东西:

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
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