gpt4 book ai didi

ruby - 如何在 Ruby 中从内存中 HTTP 发布流数据?

转载 作者:数据小太阳 更新时间:2023-10-29 07:07:38 26 4
gpt4 key购买 nike

我想上传我在运行时用 Ruby 生成的数据,就像从 block 中提供上传数据一样。

我找到的所有示例仅展示了如何流式传输必须在请求之前位于磁盘上的文件,但我不想缓冲该文件。

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

这是一个伪代码示例:

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

关于ruby - 如何在 Ruby 中从内存中 HTTP 发布流数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6027945/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com