我想上传我在 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 = "--60079rnContent-Disposition: form-data; name="file"; filename="test.file"rnContent-Type: application/x-rubyrnrnthis is just a testrn--60079--rn"
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
there's a 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) }