require 'open-uri' require 'net/http' require 'cgi' module Net class Param def initialize(k, v) @k = k @v = v end def to_multipart "Content-Disposition: form-data; name=\"#{CGI::escape(@k)}\"\r\n\r\n#{@v}\r\n" end end class FileParam def initialize(k, file) @k = k @file = file end def to_multipart content = @file.open.read "Content-Disposition: form-data; name=\"#{CGI::escape(@k)}\"; filename=\"#{File.basename(@file.name)}\"\r\n" + "Content-Transfer-Encoding: binary\r\n" + "Content-Type: #{@file.mime_type}\r\n\r\n" + content + "\r\n" end end class HTTP def post_multipart(path, data, header=nil, dest=nil, boundary="7d21f962d00c4") # :yield: self params = [] data.each do |k, v| param = nil if(v.is_a?(File)) param = FileParam.new(k,v) else param = Param.new(k,v) end params << param end query = params.collect { |p| "--" + boundary + "\r\n" + p.to_multipart }.join("") + "--" + boundary + "--" header["Content-type" => "multipart/form-data, boundary=" + boundary + " "] puts "HEADER: #{header.inspect}" post(data, query, header, dest) end end end