Sha256: ffb762f24ce0df68f0176c41769bbbe6a1880b6506bb29d871a9ce286c4b163f

Contents?: true

Size: 1.63 KB

Versions: 13

Compression:

Stored size: 1.63 KB

Contents

# -*- coding: utf-8 -*-
require 'mime/types'
module Mushikago
  module Http
    class MultipartRequest < Request
      CR = "\015"
      LF = "\012"
      EOL = CR+LF

      def to_http_request
        http_request = new_http_request
        headers.each do |key, value|
          http_request[key] = value
        end
        boundary = '----------------38117'
        http_request.set_content_type "multipart/form-data; boundary=#{boundary}"
        http_request.body = multipart_body(boundary)
        http_request.content_length = http_request.body.size
        return http_request
      end

      def multipart_body boundary='boundary'
        content = ''

        files, parameters = params.partition{|k, v| v.kind_of?(File)}
        parameters.each do |k, v|
          content << [
            %Q|--#{boundary}|,
            %Q|Content-Disposition: form-data; name="#{k}"|,
            %Q||,
            %Q|#{v}|
          ].join(EOL)
          content << EOL
        end

        files.each do |k, v|
          v.rewind
          content_type = ''
          begin
            content_type = MIME::Types.of(v.path).first.to_s
          rescue NameError => e
          ensure
            content_type = "application/octet-stream" if content_type.to_s.empty?
          end
          content << [
            %Q|--#{boundary}|,
            %Q|Content-Disposition: form-data; name="#{k}"; filename="#{File::basename(v.path)}"|,
            %Q|Content-Type: "#{content_type}"|,
            %Q||,
            %Q|#{v.read}|
          ].join(EOL)
        end
        content << %Q|--#{boundary}--|
        content << EOL
        return content
      end
    end
  end
end

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
mushikago-sdk-2.4.3 lib//mushikago/http/multipart.rb
mushikago-sdk-2.4.2 lib//mushikago/http/multipart.rb
mushikago-sdk-2.4.1 lib/mushikago/http/multipart.rb
mushikago-sdk-2.4 lib/mushikago/http/multipart.rb
mushikago-sdk-2.2 lib//mushikago/http/multipart.rb
mushikago-sdk-2.1.1 lib/mushikago/http/multipart.rb
mushikago-sdk-2.1.0 lib/mushikago/http/multipart.rb
mushikago-sdk-2.0.0 lib/mushikago/http/multipart.rb
mushikago-sdk-0.4.3 lib/mushikago/http/multipart.rb
mushikago-sdk-0.4.2 lib/mushikago/http/multipart.rb
mushikago-sdk-0.4.1 lib/mushikago/http/multipart.rb
mushikago-sdk-0.4.0 lib/mushikago/http/multipart.rb
mushikago-sdk-0.3.7 lib/mushikago/http/multipart.rb