How can I send binary data from Sinatra?

后端 未结 4 1508
深忆病人
深忆病人 2021-02-12 17:18

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

相关标签:
4条回答
  • 2021-02-12 18:00

    you can just return binary data:

    get '/binary' do
      content_type 'application/octet-stream'
      "\x01\x02\x03"
    end
    
    0 讨论(0)
  • 2021-02-12 18:04

    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
    
    0 讨论(0)
  • 2021-02-12 18:12

    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

    0 讨论(0)
  • 2021-02-12 18:16

    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
    
    0 讨论(0)
提交回复
热议问题