Ruby on rails Rails流媒体
我尝试从我的Rails服务器和我的用户流式传输一个巨大的文件。我的最终目标是通过我的服务器传输巨大的文件 我搜索并发现我必须使用self.response\u body 因此,为了测试它,我编写了以下代码:Ruby on rails Rails流媒体,ruby-on-rails,ruby,ruby-on-rails-4,stream,Ruby On Rails,Ruby,Ruby On Rails 4,Stream,我尝试从我的Rails服务器和我的用户流式传输一个巨大的文件。我的最终目标是通过我的服务器传输巨大的文件 我搜索并发现我必须使用self.response\u body 因此,为了测试它,我编写了以下代码: class HomeController < ApplicationController def index self.response_body = proc {|resp, out| 10.times do |x|
class HomeController < ApplicationController
def index
self.response_body = proc {|resp, out|
10.times do |x|
out.write "count = #{x}"
sleep 1
end
}
end
end
但是,当我请求我的Web服务器时,我得到了以下答案:
curl http://localhost:3000
#<Proc:0x0000010284d048@/Users/nicolas/Documents/development/Ruby/StreamTest/app/controllers/home_controller.rb:4>%
你知道吗
我正在瘦服务器上使用Rails 4.1.4我想您应该尝试在那里对输出进行流式处理,以下是文档
您在这里所做的是向响应体写入一个Proc。因此,您的响应主体的值将是proctos。您希望执行以下操作:
class HomeController < ApplicationController
include ActionController::Live
def index
response.headers['Content-Type'] = 'text/event-stream'
10.times.each do |x|
response.stream.write "count = #{x}"
sleep 1
end
response.stream.close
end
end
如果要流文件,需要考虑设置正确的响应头。 有两件事需要发生,以这种方式使用self.response\u body:
self.response_body需要设置为ducktyped枚举器必须实现each,并且枚举器或each方法应返回Stringy值 操作必须为客户端浏览器和机架中间件适当设置响应头,以将文件视为流式下载 下面是一个例子:class HomeController < ApplicationController
def index
headers["Content-Type"] = "text/plain"
headers["Content-disposition"] = "attachment; filename=\"index.txt\""
# Rack::Etag > 2.1.x will break streaming unless Last-Modified is set
headers["Last-Modified"] = Time.current.httpdate
headers['X-Accel-Buffering'] = 'no'
headers["Cache-Control"] ||= "no-cache"
headers.delete("Content-Length")
self.response_body = Enumerator.new do |yielder|
50.times do |x|
# Don't yield integers to the response_body unless you like getting:
# #<NoMethodError: undefined method `bytesize' for 0:Integer
yielder << x.to_s
sleep 0.1
end
end
end
end
只有在添加了新的
headers["Last-Modified"] = Time.current.httpdate