本文介绍了如何HTTP从Ruby中的内存中发布流数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想上传在运行时使用Ruby生成的数据,就像从块中上传上传的东西一样.
I would like to upload data I generated at runtime in Ruby, something like feeding the upload from a block.
我发现的所有示例仅显示了如何流式传输在请求之前必须在磁盘上的文件,但是我不想缓冲该文件.
All examples I found only show how to stream a file that must be on disk prior to the request but I do not want to buffer the file.
除了滚动我自己的套接字连接之外,什么是最佳解决方案?
What is the best solution besides rolling my own socket connection?
这是一个伪代码示例:
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
这篇关于如何HTTP从Ruby中的内存中发布流数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!