如何在 Ruby 中从内存中 HTTP 发布流数据? [英] How do I HTTP post stream data from memory in Ruby?

查看:28
本文介绍了如何在 Ruby 中从内存中 HTTP 发布流数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想上传我在运行时在 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
Content-Disposition: form-data; name="file"; filename="test.file"
Content-Type: application/x-ruby

this is just a test
--60079--
"

    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 中从内存中 HTTP 发布流数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆