class HTTP::Client::Multipart

Constants

DEFAULT_MIME_TYPE
EOL

Attributes

boundary[R]

Public Class Methods

new(files, query = {}) click to toggle source
# File lib/http/client.rb, line 327
def initialize files, query = {}
  @files    = files
  @query    = query || {}
  @boundary = generate_boundary
end

Public Instance Methods

body() click to toggle source
# File lib/http/client.rb, line 337
def body
  body      = ''.encode('ASCII-8BIT')
  separator = "--#{boundary}"

  if @query && !@query.empty?
    @query.each do |key, value|
      body << separator << EOL
      body << %Q{Content-Disposition: form-data; name="#{key}"} << EOL
      body << EOL
      body << value
      body << EOL
    end
  end

  if @files && !@files.empty?
    @files.each do |name, handle|
      if handle.respond_to?(:read)
        path = handle.path
        data = io.read
      else
        path = handle
        data = IO.read(path)
      end

      filename = File.basename(path)
      mime     = mime_type(filename)

      body << separator << EOL
      body << %Q{Content-Disposition: form-data; name="#{name}"; filename="#{filename}"} << EOL
      body << %Q{Content-Type: #{mime}}              << EOL
      body << %Q{Content-Transfer-Encoding: binary}  << EOL
      body << %Q{Content-Length: #{data.bytesize}}   << EOL
      body << EOL
      body << data
      body << EOL
    end
  end

  body << separator << "--" << EOL
  body
end
content_type() click to toggle source
# File lib/http/client.rb, line 333
def content_type
  "multipart/form-data; boundary=#{boundary}"
end

Private Instance Methods

generate_boundary() click to toggle source
# File lib/http/client.rb, line 380
def generate_boundary
  SecureRandom.random_bytes(16).unpack('H*').first
end
mime_type(filename) click to toggle source
# File lib/http/client.rb, line 384
def mime_type filename
  MIME::Types.type_for(File.extname(filename)).first || DEFAULT_MIME_TYPE
end