如何在Ruby中从内存中HTTP发送流数据?

我想上传我在Ruby中运行时生成的数据,比如从块中提取上传内容。

我发现的所有示例仅显示如何在请求之前流式传输必须在磁盘上的文件,但我不想缓冲文件。

滚动我自己的套接字连接除了最佳解决方案是什么?

这是一个伪代码示例:

post_stream('127.0.0.1', '/stream/') do |body| generate_xml do |segment| body << segment end end 

有效的代码。

  require 'thread' require 'net/http' require 'base64' require 'openssl' class Producer def initialize @mutex = Mutex.new @body = '' @eof = false end def eof!() @eof = true end def eof?() @eof end def read(size) @mutex.synchronize { @body.slice!(0,size) } end def produce(str) if @body.empty? && @eof nil else @mutex.synchronize { @body.slice!(0,size) } end end end data = "--60079\r\nContent-Disposition: form-data; name=\"file\"; filename=\"test.file\"\r\nContent-Type: application/x-ruby\r\n\r\nthis is just a test\r\n--60079--\r\n" req = Net::HTTP::Post.new('/') producer = Producer.new req.body_stream = producer req.content_length = data.length req.content_type = "multipart/form-data; boundary=60079" t1 = Thread.new do producer.produce(data) producer.eof! end res = Net::HTTP.new('127.0.0.1', 9000).start {|http| http.request(req) } puts res 

有一个Net :: HTTPGenericRequest#body_stream =(obj.should respond_to?(:read))

你或多或少地使用它:

 class Producer def initialize @mutex = Mutex.new @body = '' end def read(size) @mutex.synchronize { @body.slice!(0,size) } end def produce(str) @mutex.synchronize { @body << str } end end # Create a producer thread req = Net::HTTP::Post.new(url.path) req.body_stream = producer res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }