Class: StreamingUploader

Inherits:
Object
  • Object
show all
Defined in:
lib/abicli/commands/upload-template.rb

Defined Under Namespace

Classes: MultipartStream, StreamPart, StringPart

Class Method Summary collapse

Class Method Details

.post(to_url, params = {}, &block) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/abicli/commands/upload-template.rb', line 24

def post(to_url, params = {}, &block)
  boundary = '----RubyMultipartClient' + rand(1000000).to_s + 'ZZZZZ'
  parts = []
  content_file = nil
  
  unless params.nil? || params.empty?
    params.each do |key, value|
      if value.kind_of?(File)
        content_file = value
        filepath = value.path
        filename = File.basename(filepath)
        parts << StringPart.new( "--" + boundary + "\r\n" +
                                 "Content-Disposition: form-data; name=\"" + key.to_s + "\"; filename=\"" + filename + "\"\r\n" +
                                 "Content-Type: application/octet-stream\r\n\r\n")
        parts << StreamPart.new(value, File.size(filepath))
        parts << StringPart.new("\r\n")
      else
        parts << StringPart.new( "--" + boundary + "\r\n" +
                                 "Content-Disposition: form-data; Content-Type:application/json; name=\"" + key.to_s + "\"\r\n\r\n")
        parts << StringPart.new(value.to_s + "\r\n")
      end
    end
    parts << StringPart.new("--" + boundary + "--\r\n")
  end
  
  body_stream = MultipartStream.new(parts, block)
  
  url = URI.parse(to_url)
  
  headers = { 'accept' => 'application/json' }

  req = Net::HTTP::Post.new(url.path)
  req.content_length = body_stream.size
  req.content_type = 'multipart/form-data; boundary=' + boundary unless parts.empty?
  req.body_stream = body_stream
  
  http = Net::HTTP.new(url.host, url.port)
  res = http.request(req)
  #res = http.start {|http_proc| http_proc.request(req) }

  res
end