2017-07-28 49 views
0

我有一个控制器,需要从网络上的其他来源(例如HTTP,FTP或自定义协议套接字)获取最多100MB的数据,我正在努力研究如何在不写入临时文件然后呈现/发送临时文件的情况下呈现此响应。Rails渲染/流IO类对象没有缓冲

当轨道完成时,我可以“关闭”流,这样也很重要,所以我可以限制活动连接的数量或使用池(例如,因为某些协议具有缓慢的“连接”)。

传递IO直接渲染不起作用。 render sock

'#<TCPSocket:fd 20>' is not an ActiveModel-compatible object 

对于模板,我看到了文件说只使用render stream: true禁用缓存,但该ID还需要导轨仍要接受(也许缓存),我的对象。

回答

0

一个可能的解决方案是使用内置的Rails中live streaming supportActionController::Live模块:

Rails允许您流不仅仅是文件的更多。实际上,您可以在响应对象中传输任何您想要的内容。 ActionController::Live模块允许您使用浏览器创建持久连接。使用此模块,您将能够在特定时间点向浏览器发送任意数据。

class MyController < ActionController::Base 
    include ActionController::Live 

    def my_action 
    response.headers["Content-Type"] = "your/content-type" 

    TCPSocket.open("server", 1234) do |socket| 
     # for each chunk of data you read: 
     response.stream.write data 
    end 
    ensure 
    response.stream.close 
    end 
end 
+0

啊,看起来不错。由于“ActionController :: Live”在搜索和检查引用时从未出现过,因此必须错过某处 –